Check if a WordPress custom image size exists and provide a fallback

Sometimes you want to regenerate thumbnails to new sizes to suit a new theme, or make it retina-ready.

When a custom image size does not exist, WordPress returns the “full size version”.

But what if you want to check if a specific size exists, and fallback to the old resized version.

Let’s say you add a new custom image sizes:

<?php
if ( function_exists( 'add_image_size' ) ) {
   add_image_size( 'small', 100, 100, true ); 
   add_image_size( 'custom_size', 300, 300, true ); // this one is new
}
?>

Then you use the regenerate thumbnails plugin to resize all your images. But this can take a long time, so you might want to provide a fallback in your theme for the duration.

In the loop, check if the size you want exists before output.

Note: This example requires the Advanced Custom Fields plugin but you can modify it for any template.

<?php

// check for custom field
if( $image_id = get_field('field_name', false, false) ): 
    // if there is a custom field value in the database
	
	// get the full size version
	$full_size_image = wp_get_attachment_image_src( $image_id, 'full'); 
	
	// get the one we want
    $custom_size_image = wp_get_attachment_image_src( $image_id, 'custom_size'); 
	
	// check if they are the same
    if (!isset($full_size_image[0]) || !isset($size_we_need_image[0]) || $full_size_image[0] == $size_we_need_image[0]):
        // show the small version as a fallback, or show the full verison if you want
		$show = wp_get_attachment_image( $image_id, 'small' ); 
    else:
        // show the custom version that exists
        $show = wp_get_attachment_image( $image_id, 'custom_size' );
    endif;
    echo $show;
else : 
    // there is no custom field, so let's just grab the featured image for this post
    $image_id = get_post_thumbnail_id();
	
	// get the full size version
	$full_size_image = wp_get_attachment_image_src( $image_id, 'full'); 
	
	// get the one we want
    $custom_size_image = wp_get_attachment_image_src( $image_id, 'custom_size'); 
	
    // check if they are the same
    if (!isset($full_size_image[0]) || !isset($size_we_need_image[0]) || $full_size_image[0] == $size_we_need_image[0]):
        // show the small version as a fallback, or show the full verison if you want
		$show = wp_get_attachment_image( $image_id, 'small' ); 
    else:
        // show the custom version that exists
        $show = wp_get_attachment_image( $image_id, 'custom_size' );
    endif;
    echo $show;
    //echo 'thumb';
endif;
?>