This is the Weblog of Designer, Developer & Photographer Matthias Kretschmann more...

17thDec 09

Using The New Post Thumbnail Feature In WordPress 2.9

Wordpress Logo by kremalicious

WordPress 2.9 added a new feature which allows you to assign an image to an article to make it the post image like it’s often used in magazine style themes. This new feature along with a new template tag makes all the custom field hacks usually used for this functionality in the past obsolete. So here’s a quick walkthrough to make use of the new post thumbnail feature and of course how to make it backwards compatible.

Quick Navigation

1. Activate The Feature

Add WordPress Post Thumbnail Support To ThemeFor whatever reason you first have to activate the feature with an entry in your theme’s functions.php file in order to get the Post Thumbnail box in the Editor.

So just open up your theme’s functions.php file in your favorite editor or create it if there’s no such file in your theme folder. Add this little code snippet to this file:

add_theme_support('post-thumbnails');

For backwards compatibility you should wrap this inside a function check for the new add_theme_support:

if ( function_exists( 'add_theme_support' ) )
add_theme_support( 'post-thumbnails' );

This makes sure WordPress installation prior to 2.9 won’t get screwed up when using a theme with this new feature.

2. Add A Post Thumbnail To Your Post

Add Post ThumbnailAfter you’ve added the above mentioned code into your functions.php file there should be a new Post Thumbnail box in the WordPress editor view on the right side.

In this box click on the Set Thumbnail link and the usual Add Media dialogue will pop up where you can choose an image from your Media Library. At the end of the dialogue for the selected image there’s a new link beside the Insert into Post button called Use as thumbnail.

Add Post Thumbnail 2Click this and your chosen image will be assigned as the post thumbnail. (Unfortunately the Use as thumbnail link is missing in the dialogue which appears after uploading an image, it’s just there if you browse your Media Library.)

You can close the media dialogue now and you will see the image in the Post Thumbnail box:

Post Thumbnail added

3. Display The Post Thumbnail In Your Theme

Add to themeBasically all you have to do is to add this new template tag in your theme files where you want to display the post thumbnail, most certainly in your index.php file:

<?php the_post_thumbnail(); ?>

This template tag will display the thumbnail sized post thumbnail by default and is essentially the same as:

<?php the_post_thumbnail('thumbnail'); ?>

But of course you can grab the other sizes WordPress automatically creates when you upload an image:

<?php the_post_thumbnail('medium'); ?>
<?php the_post_thumbnail('large'); ?>

(Note: Matt left a comment on WP Engineer stating he wouldn’t recommend using these named arguments but provided no explanation for it yet.)

The code will output a generic <img /> tag with a class of wp-post-image. Needless to say this is what you can select with css to style just the post thumbnails further:

.wp-post-image {
	border: 2px solid #ccc;
}

Custom Output

If you want to adjust the generated output of the <img /> tag you can do this by using some array stuff. So let’s say you want to have the post thumbnails to be 200×200px big and another class assigned to it, you can extend the template tag like so:

<?php the_post_thumbnail(array( 200,200 ), array( 'class' => 'alignleft' )); ?>

If you want to add more than one class you can do this like so:

<?php the_post_thumbnail('medium', array('class' => 'alignleft another_class')); ?>

And you can add any attributes to the <img /> tag like a title, rel or an alt attribute. For accessibility reasons you should always add at least the alt-attribute:

<?php the_post_thumbnail('medium', array('class' => 'alignleft', 'alt' => 'alttext')); ?>

As for the title attribute this will be grabbed automatically from the entry you’ve made in your Media Library during the upload process but you even could override this too:

<?php the_post_thumbnail('medium', array('class' => 'alignleft', 'alt' => 'alttext', 'title' => 'titletext')); ?>

Respect Media Settings

Finally if you want to respect the custom sizes you or your users have set under Settings > Media you can first grab those sizes with get_option function and then put it in the array:

<?php
$width = get_option('thumbnail_size_w') / 2; //get the width of the thumbnail setting
$height = get_option('thumbnail_size_h') /2; //get the height of the thumbnail setting

the_post_thumbnail(array($width, $height), array('class' => 'alignleft'));
?>

You can also detect the Media settings for the other sizes and whether the crop setting is active or not:

<?php get_option('medium_size_w'); ?> //Width of the medium size
<?php get_option('medium_size_h'); ?> //Height of the medium size
<?php get_option('large_size_w'); ?> //Width of the large size
<?php get_option('large_size_h'); ?> //Height of the large size

<?php get_option('thumbnail_crop'); ?> //Check for crop, On=1, Off=0

4. Make It Bulletproof (a.k.a. Backwards Compatible)

With the check in your functions.php at the beginning there’s already ensured old WordPress installations will just skip this feature. But there remains one problem and before you just go ahead and update your theme(s) think about it: the old content in your blog doesn’t have a post thumbnail assigned to it through this new feature. You don’t want to have you or your theme users update all their older articles, right? And if you already use some sort of post image hack there’s probably a special function in your theme which does that.

So it’s a pretty good idea to make this backwards compatible with some quick if else voodoo, code shamelessly adapted from WP-Recipes:

if (  (function_exists('has_post_thumbnail')) && (has_post_thumbnail())  ) {
	the_post_thumbnail();
} else {
	$postimage = get_post_meta($post->ID, 'post-image', true);
	if ($postimage) {
		echo '<img src="'.$postimage.'" alt="" />';
	}
}

This first checks if the feature exists and if a post thumbnail was addd with this new feature. If it was, it simply returns the post thumbnail. If not, it falls back to whatever you’ve used in your theme before, the usual way is to check for and get the value of a special custom field named e.g. post-image and output it. You can add whatever you’ve used before inside the else statement. Et voilà, it’s nicely backwards compatible now, yay!

5. Resources And More Information

Well and that’s it. I would love to link to some smart WordPress Codex pages for these new template tags but at the time of this writing there simply isn’t anything in the Codex about this.

Oh no!

As always: before making your next coffee you should share this article on your favorite social website. Your vote is highly appreciated! After you’ve finished voting and making your next coffee or tea you could subscribe to my RSS-Feed, discuss this article or buy me my next coffee ;-)

Article Updates

12/20/2009 Added some resources and a note about the named arguments
12/20/2009 function check for add_theme_support at the beginning
12/20/2009 corrected the size array code under Custom Output
12/17/2009 Added some code examples to respect the media settings

About Matthias

Freelance designer, front-end developer and photographer who just loves creating beautiful things.

Tags: , , , , , ,

Related Posts



49 Responses

  1. mas73 says:

    Great stuff thanks for the detailed info!

  2. Or you can use my plugin Related Posts by Category with post thumbs (alternative first post image): http://wordpress.org/extend/plugins/related-posts-by-category/

  3. kevin says:

    Do you already have wp 2.9 to do that ?

  4. Thomas Veit says:

    great article!!

    i was exactly looking for a tutorial to this new feature!! can’t wait to upgrade my theme ;)

    thank you very much! bookmarked and tweeted ;)

  5. Jauhari says:

    Wonderful tips, this is exactly what I want

  6. Wiki Chaves says:

    Hi,
    I think you have a wrong code for the thumbnails resizing. you shoud use: the_post_thumbnail(array(200,200), array(‘class’ => ‘alignleft’));

    Regards,
    Wiki

  7. Great walkthrough. I think this is one of the coolest of the new features of WP 2.9. It’ll shave a pretty significant amount of time off of my template development.

    Also, great looking site you have here. I particularly like the fade-in effect on your links. It’s very cool.

  8. translexi says:

    nice one, it should be really handy for any themers out there.
    just tried 2.9 this morning and it looks promising.

  9. Ruth Maude says:

    Thanks for this great post Matthias – I linked to it in my latest post WordPress 2.9 What’s New?. I look forward to using this new feature.

  10. ZigPress says:

    Thanks very much – this is a really clear tutorial and is now bookmarked. I plan to use this feature in a new project I’m about to start.

  11. david says:

    thx for the info, if you just want to add an alt text with the post title, here’s the code:

    ‘alignleft’, ‘alt’ => $alt_text));
    }
    ?>

    Why did they add a title tag instead of alt? mistake?? lol oh well, thx for the help!

  12. Chas says:

    Thanks for the article. The CSS was very helpful.

    I am attempting to have the Post Thumbnail be a link to the post. I am having issue with the proper code and can not get the thumbnail to be a link.

  13. shoaib says:

    this is nice and m able to call the images correctly but they are not linking to the post !!! how can i do that ?

  14. gaiachik says:

    thanks, that was really helpful!

  15. Tom says:

    Thanks for this great tutorial!
    i’ll implement this on my site…

  16. CAMS says:

    anyway to call the url of the default image without it being inside img tags? its messing up trying to link to the default image…

  17. avinash says:

    nice tips. working in wordpress.

  18. Chas says:

    Does anybody know how to use the-post-thumbnail for navigation? I would like to display the next and previous links using the post thumbnail. Can this be done?

  19. Hay says:

    Of course, using a function_exists(‘the_post_thumbnail’) is not only handy for backwards compatibility for people who’ve been using a custom tag hack, but also because not using it will result in fatal php errors on anything WP < 2.9 because the function doesn't exist.

    What you could do to make things easier (and to prevent having to copy that piece of code endlessly) is simply writing a wrapper around it in your functions.php, that might also take care of any specific arguments you want to give to the function:


    function my_post_thumbnail() {
    if ( (function_exists('has_post_thumbnail')) && (has_post_thumbnail()) ) {
    the_post_thumbnail();
    } else {
    $postimage = get_post_meta($post->ID, 'post-image', true);
    if ($postimage) {
    echo '';
    }
    }
    }

    Then you can simply use my_post_thumbnail() whenever you want to use the post thumbnail.

  20. Great Post, very detailed and well laid out. Will definitely be bookmarking this for reference later if I decide to shift out timthumb.

  21. Kieran Smith says:

    Thank you for the great article! I was wondering if anyone here happened to have any experience getting the caption or link (what the image links to, rather than the URL of the image itself) attributes for the post thumbnail. It seems there should be a direct association, but yet I’ve yet to find anyone who’s connected the dots yet, at least publicly on the web. Thanks, and again, thanks for the write up!

  22. Kyle says:

    These instructions simply display the image alone.

    So how does one get this thumbnail in a post that gets wrapped by text?

  23. Eric S says:

    Is there some kind of trick to getting this thumbnail to be a link to the post/and/or to an bigger image of the thumbnail?

    • Donald says:

      To have your image link to the post, use:

      add_filter( 'post_thumbnail_html', 'my_post_image_html', 10, 3 );
      function my_post_image_html( $html, $post_id, $post_image_id ) {
      	$html = '<a href="' . get_permalink( $post_id ) . '" title="' . esc_attr( get_post_field( 'post_title', $post_id ) ) . '" rel="nofollow">' . $html . '</a>';
      	return $html;
      }
  24. imatthew says:

    А что за проблема с ссылкой http://cdharrison.com/2009/12/the_post_thumbnail-for-rss-feeds/ ? У меня не работает. Показывает 504 – что это значит?

  25. Kim says:

    Nice writeup on this new Wordpress feature. It’ll certainly get me going in my own theme framework.

  26. robert says:

    I am having a really hard time getting this thumbnail thing to work. I took all the steps listed above, however every time I post I get the same “No Thumbnail” image where my desired thumbnail is supposed to be! Can you please help me? Thank you for all the instruction you have given!

  27. YodZiaN says:

    can use this plugin with wpmu?

    and thaks for sharing

  28. Mak says:

    My blog contributors use gallery in their posts and often forget to click “Use as thumbnail” link. The end effect is that there is no thumbnail with excerpts. What is the best way to display thumbnail in this situation ?

  29. John says:

    How do you make it so the alt tag automatically inherits the filename?

  30. Hema says:

    Hi all,
    I’m struggling with ALT tag. I’ve tried all of the methods to add ALT tag in the image but none of them work. All of them show empty string. I’ve set the ALT tag for all images but it always comes empty for whetever method I use.

    Interesting though that title tag is always correct. So if title tag is displayed then why not ALT tag is displayed without any additional code?

    Is there anything else we need to change to make it automatically display ALT tag.

    Tx

  31. Eric S says:

    I just wrapped the permalink anchor around the thumbnail and it links to the post.
    But to link to a bigger image, it does not work?

    <a href=""> "alignleft post_thumbnail")); } ?>

    • Eric S says:

      Oops, well it deleted my post of the code.
      Anyways, I just wrapped the thumbnail with an anchor and the permalink code.
      If I use post thumbnail and set the condition to full it does not work.

  32. Mossack Anme says:

    How about using an external image as post thumbnail without upload it into our server???

  33. Mak says:

    Why are the “alt” tags being stripped out after inserting a Gallery into a post ? Can someone help pls ?

  34. Paul D'Amora says:

    So what if I want to get the src of the post thumbnail, for use with PHP?

  35. Mau says:

    I got this working but I see that the generated img tag is malformed. It misses the closing forward slash / so now it looks like this Any ideas on how to fix this?

  36. Nicole says:

    Thanks so much for posting this. I’m working on a layout for a personal blog that relies heavily on thumbnails and I’d heard vague mention of this feature recently but no details. This post was exactly what I need to get the feature working on my theme.

  37. Club Penguin says:

    I like the addition of this feature a lot.

  38. Arun says:

    Does this tag only work with images that are uploaded using the built-in media uploader? What if the images are uploaded via FTP to a folder on the same server, but outside of wp-content?

  39. brian says:

    Hey – I just created a new theme utilizing the new post thumbnail. I unfortuantely have older posts that dont have a thumbnail attached to them and are not showing up with the backwards compatible code. Any ideas on how to fix? Wordpress obviously created a thumbnail when the photo was uploaded, can it just use that?

    Any help would be great!

    thx

Trackbacks

  1. CSS Brigit | Using The New Post Thumbnail Feature In WordPress 2.9
  2. You are now listed on FAQPAL
  3. Wordpress: Showing an image in the excerpt – using either the_post_thumbnail( ); or Get The Image plugin « My Graphic Friend's blog

Leave a Reply

↓ Comment Guidelines ↓
  • Please remain on topic, respect other commenters and don't spam!
  • Uncivilized and spam comments will be deleted!
  • You are free to use basic HTML tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Subscribe to Comments Feed for this post

top