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:

I put a message up on facebook that I needed someone to take over the hosting of my new website, and Jo responded and left her number. I got in touch and she took control of the situation, contacting the previous host and effecting the transfer. I have been impressed with Jo’s knowledge, helpfulness and her calm manner. Thank you Jo.

(Jo Moir)