A WordPress thumbnails primer

WordPress 2.9 added some incredibly useful new thumbnail options for posts and pages. Here’s the very quick low-down on how to activate and use them.

To let WordPress know your theme supports thumbnails, add the following line to functions.php. This will add the functionality to posts and pages.

add_theme_support('post-thumbnails');

This will activate some new goodies in the admin back-end.

If you want the thumbnails active for only posts, or only pages, add the following. (Delete whichever you don’t want.)

add_theme_support('post-thumbnails', array('post'));
add_theme_support('post-thumbnails', array('page'));

Next, specify what size you want your thumbnails to be. The statement below will fit your thumbnail in a 60px by 60px box.

set_post_thumbnail_size(60, 60);

If you want your thumbnail to be cropped to the exact dimensions specified, add a third parameter like so:

set_post_thumbnail_size(60, 60, true);

Okay, that’s all the setup you’ll need for now. On to the template.

To check if the template has a thumbnail, use has_post_thumbnail(); like so:

if ( has_post_thumbnail() ) {
    // has a thumbnail
} else {
    // lacks a thumbnail
}

To show your thumbnail, use the_post_thumbnail() like so:

the_post_thumbnail();

That’s the basics.

If, however, you need multiple thumbnail sizes to use in different parts of your site, you can use the add_image_size()
function in functions.php:

add_theme_support('post-thumbnails');
set_post_thumbnail_size(60, 60, true);
add_image_size('new-size-name', 300, 200, true);

You can show this new thumbnail size with the_post_thumbnail(), like so:

the_post_thumbnail('new-size-name');

If you need your theme to be backwards compatible (with pre 2.9), then just use the following code wherever you want to use these new functions:

if ( function_exists('add_theme_support') ) {
    // do your stuff
}

That’s all folks. Happy thumbnailing.

Date: February 25, 2010
Tags: , , ,

Leave a Reply