How To Customize Post Thumbnails In WordPress

Post Thumbnails were introduced in WordPress 2.9, but there wasn’t a ton of information about how to use them in your current theme.

The theme that I use on a lot of my sites already has support for post thumbnails, but there was no documentation on how it worked. I spent quite a bit of time trying to understand how it worked, and how I could modify it to work for my specific needs.

I found a reference to the post_thumbnail function in my function.php file, with a notation from the theme author that said the image sizes should be width 610 px, height 320 px. If I used an image of that size, it was then resized down to 212px by 145px.

The problem was that if I had an image outside of those dimensions, it resized to a different size than 212×145, and it made the homepage look like a mess as a result. It’s just not feasible to make every single image exactly 610×320, so it was time to dig a little deeper.

After a few failed attempts, I finally found the answer in the WordPress Codex.

Add/modify the following code to your function.php:

if ( function_exists('add_theme_support') ) {
add_image_size( 'home-thumb', 212, 145, true );

Now the key is that add_image_size line.. That’s telling WordPress to do a hard crop of the image, making it 212×145. You can change those values to whatever is appropriate for your theme.

Now you need to call the function from your index.php file:

if ( has_post_thumbnail() ) { the_post_thumbnail('home-thumb', array('class' => 'alignleft post_thumbnail')); }

The home-thumb arguement tells it to use the image size you defined in the function.php file, rather than the default (which wasn’t appropriately sized for my theme). The array sets the class, so that the image is properly aligned.

It looks simple now, but you’d be amazed at how long it took me to find the right code to make everything display as I wanted it to!

Lastly, make your life easy, and install the Auto Post Thumbnail plugin. This plugin automatically makes the first image you upload within a post the featured image. And even better, it’ll go through all of your old posts, and do the same!

So I hope this helps anyone else out there that was struggling with this like I was. If you have any questions, leave a comment and I’ll do my best to assist.

Enjoyed this post?
Subscribe to Zander Chance via RSS Feed or E-mail and receive daily news updates!

Submit to Digg  Stumble This Story  Share on Twitter  Post on Facebook  Post on MySpace  Add to  Submit to Reddit  Fave on Technorati

Leave a Reply