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.

https://code.tutsplus.com/tutorials/add-an-automatic-featured-image-to-blog-posts-based-on-category--cms-22664?_ga=2.257833033.375895460.1662704905-1858649747.1647844437
«
»
ACF (3)
Admin Column (4)
Breadcrumbs (2)
CSS (6)
Custom post types (4)
Custom Taxonomies (3)
Customizer (4)
Hooks & Filters (3)
Jquery (9)
LAMP (10)
Login (5)
Meta boxes (6)
Multisite (2)
My Code (1)
Open Graph Meta Tags (1)
Redirects (2)
SEO (4)
Theme Building (5)
Title Tags (2)
Typography (3)
Uncategorised (54)
User Roles & Capabilities (2)
White labeling (9)
Working with Images (11)
Working with videos (2)
WP Database (1)