Add an Automatic ‘Featured Image’ to Blog Posts Based on Category

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:

This tutorial will work through these steps:

  1. registering the category taxonomy for attachments
  2. setting up categories and adding images to them
  3. 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.