How to Add Post Thumbnails to Your WordPress Theme

Many blog posts have been using custom fields to add thumbnail images to their post excerpts. With WordPress 2.9, there is now a built-in functionality to easily add “featured images” to your posts by registering post thumbnails in our themes.

First, you will need to enable the post thumbnail functionality for your theme by pasting the following into your functions.php file:

Source code    
// add post-thumbnails support

Once enabled, you can insert the thumbnail into the loop of your WordPress theme by calling

Source code    
<?php the_post_thumbnail(); ?>

The trick is, that when you set your featured image, it may not be exactly the thumbnail size that you would like. There are a couple of ways to control your thumbnail size. First, you can go Settings > Media and manually set the thumbnail size:

Set Thumbnail Size

The other option is to add another line to your functions.php file:

Source code    
// add post-thumbnails support
set_post_thumbnail_size(100, 100, true);

where the variables are (width, height, crop? (true/false)).

In our case, we were updating an old theme that used custom fields to call our thumbnail images. We wanted to switch to the new the_post_thumbnail() call simply because it makes it much easier to insert thumbnail images. However, when updating the theme, we did not want to have to go back and update every single thumbnail image that was inserted using the custom field.

All we had to do was add an extra conditional statement into our loop to first check to see if there was a post-thumbnail, and if not, check to see if there was a custom field thumbnail. Our code is below:

Source code    
<?php if ( has_post_thumbnail() ) : ?>
    <div class="thumbnail"><?php the_post_thumbnail('thumbnail'); ?></div>
 <?php  elseif( get_post_meta($post->ID, "thumbnail", true) ): ?>
    <div class="thumbnail">
        <img src="<?php echo get_post_meta($post->ID, "thumbnail", true); ?>" width="100" height="100" alt="<?php the_title(); ?>" /></div>
 <?php  else: ?>
<?php endif; ?>

This is just a basic introduction on how to get started. There are other posts that go into more detail and complexity on the things you can do with the_post_thumbnail().

Leave a Comment