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 200x200px 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



99 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

  40. Kenn says:

    I have set up the thumbnail-size to 200 x 140px (w x h) in the mediaoptions in WP, and have no problem showing this with a class on my home.php using 'thumb-hpbottom')); ?>

    Now I want to use the thumbs in a loop of a specific category on a page:

    have_posts()) : $recent->the_post();?>

    <a href="" rel="bookmark"> 'alignleft', 'alt' => 'alttext')); ?>
    <a href="" rel="bookmark">


    As you can see, the the_post_thumbnail triggers 90 x 90 px thumb, but on my page, it will display the proportions, so 90 x 90 will become something like 65 x 90 px. It will not display a square image!

    Can anyone figure this out?

    • Kenn says:

      Man – the code screwed up!

      My problem is that I have defined a thumb-size in WP admin at 200 x 140 px. This works fine on my home.php.

      I have used your suggestions so when using eg. 90 x 90 px in a loop, the images will display a proportionals size like 65 x 90 px and NOT 90 x 90 px.

      Any suggestions, please?

  41. Kenn says:

    I SOLVED IT!!!

    I added:
    ‘add_image_size( ‘postliste-thumbnail’, 90, 90, true );’
    to the functions.php

    Then I added this in the loop:
    ‘php the_post_thumbnail(( ‘postliste-thumbnail’ )’…

    meaning that now I have a thumb on the home.php in 200 x 140 px and a 90 x 90 px for every post where I put the code.

    nice …

  42. Thanks for this! I adapted some of the functionality to allow the image to integrate with Fancybox.

    If your interested, I made a quick note of how it’s done, http://davidgoldberg.me/tutorial/using-wordpress-post-thumbnail-with-fancybox/.

  43. Javi A. says:

    Hi everybody and thanks to the author for this helpful article.

    I was trying to show thumbnails in my post excerpts.
    I’m trying to get the easiest and more authomatic way for showing them.
    This is my plan: to show a thumbnail with the same name as the post id + jpg (or gif or so on).
    Does anybody know what should I do for getting it?

    Thanks a lot in advance !

  44. Angel says:

    I am having a problem getting the thumbnail to show in my child theme “Gallery.” Here is the string I have in the functions.php file to have my thumbnails show on the home page.

    here is a link to the demo site: http://www.reinnovating.com/yourbusiness/

    I’ve also tried {the_post_thumbnail();} instead of {get_the_post_thumbnail();} and cannot get the thumbnails to show

    Any ideas?

  45. Huw says:

    Hi,
    Great tut. Thanks! One problem i am getting whilst coding on my local machine. The thumbnail is staying at 150×150? I have changed the media settings to 564×206.
    Is there anything that could be interfering with this?

    Is it possible to email my coding for you to inspect?

    Thanks again!

  46. Thanks for such a comprehensive writeup. It saved me a great deal of time this weekend and worked like a charm.

  47. agrisevdasi says:

    My problem is that I have defined a thumb-size in WP admin at 200 x 140 px. This works fine on my home.php.

  48. hitbedava 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 ;)

  49. onlynpara 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

    • Javi A. says:

      I was thinking about that problem that is the same as mine.
      The solution I’ve found is to design an icon or a thumbnail for every post.
      Then you set the right code in your post page and that’s all.
      The right code should be one that chooses the thumbnail named as the post (the same post number).
      Excuse me for my english.

  50. Brian says:

    I got it to work but it’s displaying the image on the right side of the post and not the left on the main page. how to I fix this? thanks!

  51. Ellen says:

    Thanks for this easy to understand article! I just tried it out on my new theme design and it works great :-)

  52. Vanessa says:

    OMG! Can’t believe I hadn’t heard about this before! I’ve been looking for the easy way to do this. Thank you thank you thank you!

  53. karthik says:

    I have used wpmu 2.9.2 and default theme. Then add code in functions.php But it didn’t work. Any help please?

  54. Dat Tai says:

    great post,thanks alot

  55. pornoizliyor says:

    I got it to work but it’s displaying the image on the right side of the post and not the left on the main page. how to I fix this? thanks!

  56. I have been searching this tutor for long time, thanks for the great tutor..

  57. DigitechLife says:

    I Thinks this tutorial is easy to apply.. thanks you..

  58. George Barn says:

    I found that some change is happen or going to be happen, there has been a code change.

    You need to use the_post_thumbnail_*

    Try Check dougal.gunters.org/blog/2009/12/11/post-thumbnails-changes

  59. Ilie Ciorba says:

    Thank you a lot, very useful!

  60. Great Post, Thanks for useful tips..

  61. Tatva168 says:

    Hi

    i have installed a wordpress component for joomla but when i try this feature i am not geeting any post thumbnail box on editor page in admin side

    i have tried by putting in /wp-content/themes/sk/functions.php
    if ( function_exists( ‘add_theme_support’ ) ) {
    add_theme_support( ‘post-thumbnails’ );
    }

    what will be reason? any one can help fast?

  62. Walter says:

    I couldn’t get the “resize” working. First all thumbs were square. Whatever I put in the array .. say array(186,80) would render a 80×80 thumbnail.

    So I added the

    in tunctions.php ,
    then I did : the_post_thumbnail( ‘joint-thumbnail’) in index.php … didn’t work. It gave me a 138×80 ???
    There were no CSS entries, only element style (google chrome inspect element). The size was set inline, like … so CSS could not override it.

    I solved it by adding an inline STYLE element like this:
    the_post_thumbnail( ‘joint-thumbnail’, array(‘class’ => ‘alignleft post_thumbnail’, ‘style’ => ‘width: 186px; height: 80px;’));
    That did it.. but it’s kind of NUKE that stubborn ass way. What is happening here?

  63. Arian says:

    Excellent, I was not sure how to use it. I will start implementing this in my word press themes. Thanks!

  64. Chais Meyer says:

    Thank you so much for this post, it really helped me configure my site with WP 2.9

  65. Desik says:

    Hello,

    is there a way to customize the alt text? lets say i want to use something like:

    alt=”my text ”

    I have the alt tag working but I can only show the post title, I would like to use predefined text for some of my alt tags plus the tittle of the post.

    thanks in advance.

  66. Desik says:

    Forgot about php code in comments, here is the code I want to use:

    alt="my text "

    Basically the alt tag should be my custom text plus the post title.

  67. Superb Tips, Thank you

  68. Kevin says:

    Wonderful tips,thanks a lot.

  69. “”After 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.”"

    No such Post Thumbnail box appeared for me in step 2, after completing the first step… I’ve got a clean install of WP3 :( Not sure if others will have this problem, but it’s worth checking…

  70. Scratch that last comment! I didn’t realise the name had been changed from “Post Thumbnail box” to “Featured Image”… sorry to scare you all… Don’t have time to investigate this fully…

  71. club penguin says:

    Thanks for the awesome tutorial, I’ve been looking for a guide like this for a while.

  72. gkeeper says:

    Are this tutorial work on WP 3.0 ?

  73. Michael Montgomery says:

    Does anybody know how I can retrieve the image alt text . I need to display this in a span (The Originally Entered Alt Text) ::: Any Help would be appreciated

  74. PashaFFresh says:

    it was very interesting to read.
    I want to quote your post in my blog. It can?
    And you et an account on Twitter?

  75. Qaxooti says:

    I’m trying to use the post thumbnail slideshow on my website with various different themes I’ve downloaded, but I just can’t get it to work right. I am running WordPress 3.0 and have set the featured images correctly for a couple of posts. In addition, I’ve gone to the settings and set the slideshow to use featured posts from “uncategorized” (the category in which all of my posts are).

    It doesn’t work. What happens is, if no featured images are set, it will simply list a snippet of the last 5 posts (without images). If I add a featured image to a post, it will skip that post altogether and list the other posts with their snippets.

    Any suggestions? I feel like I’ve tried everything…

    I know it’s different in WordPress 3.0 than 2.9, but I’m just looking for any help I can get. Thanks.

  76. Joy says:

    I use wordpress 3.0 too and I have the problem. I have done step 1 and then I tried to find “Post thumbnail box” on step 2 but there is no box at all. WHat should I do?

  77. Asgeir Hoem says:

    Hi, and thanks for a thorough article. Is there a way to prevent the function from generating size-attributes altogether? I’d like to control the image sizes with CSS, and the height=”" and width=”" attributes are messing it up. Any hints are greatly appreciated!

  78. saat says:

    thank you nice post

  79. Mikael says:

    Thanks a lot !

  80. Agus Suhanto says:

    Your explanation is very clear. The documentation from the WordPress codex even doesn’t explain to this kind of details.

    BTW, I also made a post about post-thumbail feature of WordPress here: http://suhanto.net/the-importance-of-featured-image-in-wordpress/. I hope it can complement this posting in certain area.

  81. Mark says:

    Thanks for the tip. But I was trying to make this work for pages with featured thumbnail. I can’t seem to make it show on the homepage. Does this only work on posts?

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