Last Updated: January 20, 2020
·
1.402K
· hasinhayder

Regenerate WordPress thumbnails with predefined sizes

If you are a theme developer then you are obviously familiar with add_image_size() function, which is actually pretty handy in defining custom sizes. Each of these custom sizes can later be used from your theme. One of the benefits of defining custom size is that WordPress will manage cropping according to these sizes automatically. But, at the same time, WordPress will not do anything for the images which were uploaded before registering these sizes. In such cases, calling this function can save your time by regenerating thumbnails for all the previously uploaded images. Remember to place them in your functions.php, and call only once.

include_once( ABSPATH . 'wp-admin/includes/image.php' );
function regenerate_all_attachment_sizes() {
    $args = array( 'post_type' => 'attachment', 'numberposts' => 100, 'post_status' => null, 'post_parent' => null, 'post_mime_type' => 'image' ); 
    $attachments = get_posts( $args );
    if ($attachments) {
        foreach ( $attachments as $post ) {
            $file = get_attached_file( $post->ID );
            wp_update_attachment_metadata( $post->ID, wp_generate_attachment_metadata( $post->ID, $file ) );
        }
    }       
}
regenerate_all_attachment_sizes(); 

That's it, folks! Enjoy.