Using featured images in post archives is a common feature of themes, but sometimes you might want to use featured images a bit differently. Occasionally I’ve worked on sites where the images to be displayed relate to the category a post is in and not to the post itself. Instead of adding the same featured image to every post in each category, it would be much simpler if I could just assign the category to each of my images, and then display the featured image for the category with the post.
Examples of when you might want to do this include:
- when each post is each associated with a brand and you want to display the logo
- when each post is associated with one of a number of places and you want to display an image (or map) of that place
- when each post relates to a given topic (for example on a learning site) and you want to display an icon for that topic
- when posts are part of a number of series (as is sometimes the case on this site) and you want to use an image to identify each series
In this tutorial I’ll be using some of the techniques I’ve already demonstrated in two earlier tutorials:
- Applying categories to attachments: we’ll need to do this so that each category has its own attachments.
- Creating a ‘featured image’ for a category: in this tutorial I demonstrated how to create ‘featured images’ for categories and then display them on the category archive. This tutorial is slightly different as I’ll be displaying the category images on the main blog page.
This tutorial will work through these steps:
- registering the category taxonomy for attachments
- setting up categories and adding images to them
- in the loop, identifying which category a post is in and then running a query to output the attachment from that category
Note: For each post only one category will be identified, and for each category only one image will be output (the most recent).
I’ll also look at how you can adapt this technique for other archive pages, such as custom post type archives.
Add an Expiry Date to WordPress Posts »