Automate Your WordPress Featured Images Based on Post Category

If you manage a WordPress blog, you know that creating unique featured images for each post can be time-consuming, especially for shorter posts. Wouldn’t it be great if you could standardize your featured images based on each post’s category? That’s precisely what we’ll cover in this tutorial – automatically setting a default featured image for a post based on its category, using a simple snippet of PHP code. This way, you can not only maintain consistency across your posts but also save significant time and effort.

First, let’s dive into where this code needs to be placed. We’re going to use the functions.php file within your child theme to insert our PHP function. The role of a child theme is to let you modify your site’s functionality without changing your original theme files.

Here’s the PHP code that will help you set the default image for a post based on its category:

/**
 * Sets the default image for a post based on it's category
 */
function setDefaultPostImage(): void
{
    global $post;
    if (has_post_thumbnail()) {
        return;
    }

    // Set default image based on category ID
    $categories = get_the_category($post->ID);
    $category_id = $categories[0]->cat_ID;
    $default_images = array(
		1 => '2023/02/jack-whitworth-icon-md.webp', //Uncategorised
        3 => '2023/03/jack-whitworth-python-logo.webp', //Python
		25 => '2023/02/jack-whitworth-icon-md.webp', //Portfolio
        32 => '2023/03/jack-whitworth-php-logo.webp', //PHP
    );

    if (array_key_exists($category_id, $default_images)) {
        $image_url = content_url() . '/uploads/' . $default_images[$category_id];
        $image_id = attachment_url_to_postid($image_url);
        if ($image_id) {
            set_post_thumbnail($post->ID, $image_id);
        }
    }
}
add_action('publish_post', 'setDefaultPostImage');

In a nutshell, here’s how this function works:

  1. When a post is published, it checks if a thumbnail already exists for that post.
  2. If there is no thumbnail, it fetches the ID of the main category assigned to the post.
  3. The category IDs are then used as keys within a key/value pair array to map specific images to each category.
  4. Based on these key/value pairings, the function assigns the appropriate image to the post using the category ID.

This straightforward solution enables you to automate the process of assigning featured images, providing a more seamless and efficient blogging experience.

Leave a Reply

Your email address will not be published. Required fields are marked *