How to Check if Custom Image Size Exists in WordPress
When working on a custom WP Theme last night, I’m looking into how to check if custom image size exists in WordPress posts or pages. Since WordPress version 2.9, the core introduce and add support for ‘auto image size’ for each WordPress posts. Without relying on third party thumbnail re-sizer such as Timthumb, user now can upload images into the write post panel and the WordPress core will auto create your available add_image_size() set image size. learn more about add_image_size() here.
You can grabbed your existing ‘image size’ by using the_post_thumbnail() anywhere in your template, provide if the ‘image size’ existed in the first place. WordPress core already include default ‘image size’ when you uploaded any images into your media or attachment settings. This include ‘image size’ for thumbnail, medium, large and full. The following image size can be showed with below code.
[css]the_post_thumbnail(‘thumbnail’); // Thumbnail (default 150px x 150px max)
the_post_thumbnail(‘medium’);// Medium resolution (default 300px x 300px max)
the_post_thumbnail(‘large’);// Large resolution (default 640px x 640px max)
the_post_thumbnail(‘full’); // Full resolution (original size uploaded)[/css]
But what if you have a different add_image_size() that you want to use instead of the default one. You want to grabbed your own custom image size first before WordPress core kick in and use the closest available image size by default. Here’s how you can accomplished this:
First open your functions.php and check for your custom image size, it will look something like this
[css]add_image_size( ‘my-thumbnail’, 100, 100, true ); //hard crop 100×100[/css]
And now in your template post loop, you can grabbed your ‘custom image size’ first before resolving to default ‘thumbnail’ by adding similar code below.
$the_thumbnail_src = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), "my-thumbnail" );
$thumbnail_src = $the_thumbnail_src;
//change this to exact WxH of your custom image size
$check_thumb = strpos($thumbnail_src, ‘100×100’);
// if custom image size exist
if( $check_thumb ):
echo the_post_thumbnail(‘thumbnail’); // if not, use default thumbnail
That’s all, its easy right? Now you can check if your own set of custom image size exist or not before WordPress core use the default or closest ‘image size’.
If you want to regenerate your own set of custom image size, you can try Ajax Thumbnail Rebuild which can help you re-build your featured images and existing or new ‘image size’.