How to: Enable Featured Images in Your WordPress Theme

3rd January 2012

It has always been possible to effectively attach an associated image to an article, either by uploading to the media library and creating a query, creating a custom field or installing a plugin, it’s just been a bit of a pain in the butt and required you to handle all of the cropping yourself. Cries of relief then as WordPress 2.9 was released at the end of 2009, when this became a native function. In this and all subsequent versions you can attach a Featured Image to any post or page and pull it through into your theme with just one simple line of code, giving you a clean and standardised way to create essential elements such as thumbnail images.

Enabling Featured Image Support

Featured Image support needs to be enabled on a theme by theme basis. To do so, open or create the functions.php file in your theme’s root (wp-content/themes/your-theme-name).

To add thumbnail support for all post types, add this command somewhere after the opening <?php:

Or, to enable thumbnails for just posts:

Or, just pages:

Setting Sizes

You have two options here – box resizing and hard cropping. Box resizing shrinks an image proportionally (without distorting it), until it fits inside the box you’ve specified. The whole image will show, but to get it to fit in the box it won’t always be the same size. To set your thumbnail using box-resizing, add this command below the line you created to add theme support:

Your second option is hard cropping, where the image is cropped to match the target aspect ratio, and is then shrunk to fit in the specified dimensions exactly. You’ll get the exact size you asked for, but parts of your image may have to be cropped out to get the image to fit. To set your thumbnail using hard cropping, add this command below the line you created to add theme support:

Displaying Featured Images in the Theme

Now you can add your Featured Image, if it exists, to the loop:

You can get around the problems associated with both kinds of sizing by uploading image with the correct aspect ratio.

Creating Multiple Sizes

What if, for example, you want to display a hard cropped square thumbnail on your category pages but a box resized rectangular header image within your individual posts? The answer is simple – just specify additional custom sizes:

And pull it through into the theme:

Leave a Reply

What our customers say:

I recently hired Jo to give me some basic HTML and website editing training. I learnt so much in one hour, and she really demonstrated her knowledge, without jargon, and demystified some of the magic of web programming. I would recommend Jo to anyone who needs to brush up on their HTML knowledge, but I would also hire her for larger projects. She was a pleasure to work with and I look forward to working with her again in the future.

Ruth Holroyd