First Image of Post As Thumbnail Or An Default Image If Thumnail Not Set In WordPress

From past few days I was busy in doing some coding for my WordPress blog, In this theme I had added Thumbnail support which was introduced by WordPress back in 2.9 version.

You can activate it by just updating your functions.php and index.pho file in your theme folder, but as I had started using thumbnail back in February 2012 but this blog is running from 4 years so there are some old post which don’t had any thumbnail.

As there are lots of post so its not possible to set thumbnail for all manually, So I decided to set first image from post as thumbnail of those old post which don’t had any thumbnail, but what if your post don’t had any thumbnail or image in post?

In that case you can ask WordPress to display a specific image as your thumbnail, So here we go.

Activate Thumbnail

First activate your thumbnail support so for this open your functions.php file and add following code in it :-

add_theme_support( ‘post-thumbnails’ );
set_post_thumbnail_size( 64, 64, true );

You can define size as per your needs, true here means that it will hard crop your image while using thumbnail. Now open your index.php and add following code :-

<?php if ( has_post_thumbnail() ) {
the_post_thumbnail();
}?>

Now if you navigate to Post –> Add New, now you will see a new option of Featured Image in that page.

Featured_Image

First Image As Your Thumbnail Else A Specific Image

Now if your old post don’t has any featured image set then it wont display any thumbnail for it, so you can call for first image used in post to display as thumbnail, for this add following in your functions.php :-

function catch_that_image() {
global $post, $posts;
$first_img = ”;
ob_start();
ob_end_clean();
$output = preg_match_all(‘/<img.+src=[‘”]([^'”]+)[‘”].*>/i’, $post->post_content, $matches);
if(count($matches [1]))$first_img = $matches [1] [0];
return $first_img;

Now we need to update our index.php file so that it will display your post first image as thumbnail and if post don’t had any image then a specific image, so final code will look like this in index.php :-

<?php if ( has_post_thumbnail() ) {
the_post_thumbnail();
}
elseif( catch_that_image() ) { ?>
<img src=”<?php echo catch_that_image(); ?>” width=”64″ height=”64″ alt=”<?php the_title_attribute(); ?>” />
<?php } else { ?>
<img src=”Your Specific Image URL” width=”64″ height=”64″ alt=”<?php the_title_attribute(); ?>” />
<?php } ?>

That’s it, Now you will get a thumbnail for all post in your WordPress no matter you had set it or not or even if your post don’t had any image.

Some handpicked devices for you