Trusted WordPress tutorials, when you need them most.
Beginner’s Guide to WordPress
WPB Cup
25 Million+
Websites using our plugins
16+
Years of WordPress experience
3000+
WordPress tutorials
by experts

How to Set A Fallback Featured Image Based on Post Category in WordPress

Editorial Note: We earn a commission from partner links on WPBeginner. Commissions do not affect our editors' opinions or evaluations. Learn more about Editorial Process.

Are you looking for a way to set a default post thumbnail for specific WordPress categories?

If you have articles that don’t have a featured image, or if you want all the posts in a category to have similar thumbnails, then you can set a fallback image for each category so no blog posts will be left out.

In this article, we will show you how to set the default fallback featured images for specific categories in WordPress.

How to set fallback featured image based on post category in WordPress

Why Add a Fallback Featured Image for Post Category?

Let’s say you have a WordPress blog where you assign a single category to each post. You can assign all posts in that category to show the same fallback image if they don’t have a featured image for some reason.

Another benefit of adding a fallback image for a post category is if your category archive pages get a lot of search traffic, then it makes them more engaging and attractive.

That said, let’s see how you can add a fallback image based on the post category using a WordPress plugin and custom code.

Setting Fallback Featured Image in WordPress Using a Plugin

By default, WordPress doesn’t offer an option to add images to your post category pages. However, you can easily set a fallback image for post categories using a WordPress plugin.

First, you’ll need to install and activate the Category and Taxonomy Image plugin. For more details, please see our guide on how to install a WordPress plugin.

Upon activation, you can head to Settings » Taxonomy Image from the WordPress admin panel. Next, you can click the ‘category’ checkbox to include taxonomy images in your post categories as a fallback.

Enable taxonomy images for category

Don’t forget to click the ‘Save Changes’ button when you’re done.

After that, you can go to Posts » Categories from your WordPress dashboard. You’ll see an ‘Image’ field appear when adding a new category or editing an existing one.

New image field for categories

Simply enter an image URL you want to add to your WordPress category. For more details on that, please see our guide on how to get the URL of images you upload in WordPress.

Now, when you publish a blog post with no featured image assigned, then WordPress will use the picture you just set for your category.

Here is a preview of the image we used on your demo site.

Preview of fallback image with plugin

That’s all! You’ve now successfully added a fallback image based on the post category.

Setting Fallback Featured Image in WordPress without a Plugin

You can also configure a fallback image for post categories without using a WordPress plugin. However, this method is not recommended for beginners as it involves code snippets.

The first thing you need to do is create images for your WordPress categories. Use category slug as your image file name and save them all in the same format, like JPG or PNG.

Next, you can upload your category images to your WordPress site from Media » Add New.

Upload images to media library

WordPress will store your category images during the upload and create image sizes defined by your theme.

After uploading category images, you need to move them to a different directory. Simply connect to your website using an FTP client and go to the /wp-content/uploads/ folder.

Uploads folder in WordPress

The category images you uploaded will be stored in the month folder, like /uploads/2022/08/.

Go ahead and open this month’s folder.

Media uploads organized in year and monthly folders

You can see our guide on where WordPress store image on your site for more information.

Next, create a folder on your computer’s desktop and name it category-images. Now download all your category images and all the sizes WordPress made for them to this new folder on your desktop.

Once the download is finished, you need to upload the category-images folder to your /wp-content/uploads directory. Doing this will allow you to have all your category image sizes in a separate folder which is easy to call into your theme.

For more details, please see our guide on how to use FTP to upload files to WordPress.

Displaying Category Image as Default Fallback Featured Image

Next, we will show you how to display one of those images as the fallback featured image when a post in a category does not have one set.

This method does involve copying and pasting code, and we don’t normally recommend users edit their theme files. Small mistakes can make big errors on your site.

An easier way to add code to your site is by using WPCode. It’s the best WordPress code snippet plugin, allowing you to safely and easily manage custom code on your site.

First, you’ll need to install and activate the free WPCode plugin. For more details, please see our guide on how to install a WordPress plugin.

Next, you can go to Code Snippets » + Add Snippet in your WordPress admin panel to add a new snippet. Then just click on the ‘Add New’ button.

Click 'Add New Snippet' in WPCode

After that, you can either add custom code or use a snippet from WPCode library.

For this, you will be using your own custom code, so hover over ‘Add Your Custom Code (New Snippet)’ option and click the ‘Use Snippet’ option.

Add custom code in WPCode

Now add a name for your snippet, which can be anything to help you remember what the code is for.

Since the code has PHP, make sure to choose PHP Snippet as the ‘Code Type’ from the dropdown menu.

Add a fallback image

After that, simply copy the following code snippet and paste it into the ‘Code Preview’ field.

/**
 * Plugin Name: Category Thumbnail Fallback
 * Description: Use the category image as fallback when the post does not have a featured image
 */

class WPBCategoryThumbnailFallback
{
    protected static $taxonomies = ['category'];

    protected $nonceId = 'wpb_category_thumb_fallback_none';
    protected $fieldId = 'wpb_category_fallback_post_image';

    public $taxonomy;

    protected function __construct($taxonomy)
    {
        $this->taxonomy = $taxonomy;
    }

    public static function init()
    {
        foreach (static::$taxonomies as $taxonomy) {
            $_self = new self($taxonomy);

            add_action('admin_enqueue_scripts', [$_self, 'scripts']);

            add_action("{$taxonomy}_add_form_fields", [$_self, 'add']);
            add_action("{$taxonomy}_edit_form_fields", [$_self, 'edit'], 99, 2);

            add_action("created_{$taxonomy}", [$_self, 'saveTerm'], 10, 2);
            add_action("edited_{$taxonomy}", [$_self, 'editTerm'], 10, 2);

            add_filter("get_post_metadata", [$_self, 'fallback'], 99, 5);
        }
    }

    public function scripts($hook_suffix)
    {
        if (in_array($hook_suffix, ['term.php', 'edit-tags.php'])) {
            $screen = get_current_screen();

            if (is_object($screen) && "edit-{$this->taxonomy}" == $screen->id) {
                wp_enqueue_media();

                wp_add_inline_script('media-editor', $this->inlineScript());
            }
        }
    }

    public function add()
    {
        ?>
        <div class="form-field upload_image-wrap">
            <label for="upload_image">Image</label>
            <input id="upload_image" type="hidden" size="36" name="<?php
            echo esc_attr($this->fieldId)
            ?>" value=""/>
            <div id="wpb-category-image-preview" style="max-width: 150px; max-height: 150px;"></div>
            <input id="upload_image_button" class="button" type="button" value="Upload Image"/>
            <p>Enter a URL or upload an image</p>
        </div>
        <?php
        wp_nonce_field($this->nonceId, $this->nonceId);
    }

    public function edit($term, $taxonomy)
    {
        $value = get_term_meta($term->term_id, $this->fieldId, true);
        $image = wp_get_attachment_image((int)$value);
        ?>
        <tr class="form-field upload_image-wrap">
            <th scope="row"><label for="name">Image</label></th>
            <td>
                <label for="upload_image">
                    <input id="upload_image" type="hidden" size="36" name="<?php
                    echo esc_attr($this->fieldId)
                    ?>" value="<?php
                    echo esc_attr($value)
                    ?>"/>
                    <div id="wpb-category-image-preview" style="max-width: 150px; max-height: 150px;"><?php
                        echo $image;
                        ?></div>
                    <input id="upload_image_button" class="button" type="button" value="Upload Image"/>
                </label>
                <p class="description">Enter a URL or upload an image</p>
            </td>
        </tr>
        <?php
        wp_nonce_field($this->nonceId, $this->nonceId);
    }

    public function saveTerm($term_id, $tt_id)
    {
        $data = array_filter(wp_unslash($_POST), function ($value, $key) {
            return in_array($key, [$this->nonceId, $this->fieldId]);
        }, ARRAY_FILTER_USE_BOTH);

        if (
            empty($data) ||
            empty($data[$this->nonceId]) ||
            ! wp_verify_nonce($data[$this->nonceId], $this->nonceId) ||
            ! current_user_can('manage_categories')
        ) {
            return null;
        }

        if (empty($data[$this->fieldId]) || empty(absint($data[$this->fieldId]))) {
            return delete_term_meta($term_id, $this->fieldId);
        }

        $value = absint($data[$this->fieldId]);

        return update_term_meta($term_id, $this->fieldId, $value);
    }

    public function editTerm($term_id, $tt_id)
    {
        $this->saveTerm($term_id, $tt_id);
    }

    public function fallback($null, $object_id, $meta_key, $single, $meta_type)
    {
        if (
            $null === null &&
            $meta_key === '_thumbnail_id'
        ) {
            $meta_cache = wp_cache_get($object_id, $meta_type . '_meta');

            if ( ! $meta_cache) {
                $meta_cache = update_meta_cache($meta_type, [$object_id]);
                $meta_cache = $meta_cache[$object_id] ?? null;
            }

            $val = null;

            if (isset($meta_cache[$meta_key])) {
                if ($single) {
                    $val = maybe_unserialize($meta_cache[$meta_key][0]);
                } else {
                    $val = array_map('maybe_unserialize', $meta_cache[$meta_key]);
                }
            }

            if (empty($val)) {
                $fallbackImageId = $this->getPostFallbackImageId($object_id, $single);

                if ( ! empty($fallbackImageId)) {
                    return $fallbackImageId;
                }
            }

            return $val;
        }

        return $null;
    }

    public function getPostFallbackImageId($postId, $single)
    {
        $terms = get_the_terms($postId, $this->taxonomy);

        if (empty($terms) || is_wp_error($terms)) {
            return null;
        }

        foreach ($terms as $term) {
            $fallbackIdFromCategoryId = get_term_meta($term->term_id, $this->fieldId, $single);

            if ( ! empty($fallbackIdFromCategoryId)) {
                return $fallbackIdFromCategoryId;
            }
        }

        return null;
    }

    public function inlineScript()
    {
        return "jQuery(document).ready(function ($) {
            var custom_uploader;
            $('#upload_image_button').click(function (e) {
                e.preventDefault();
                //If the uploader object has already been created, reopen the dialog
                if (custom_uploader) {
                    custom_uploader.open();
                    return;
                }
                //Extend the wp.media object
                custom_uploader = wp.media.frames.file_frame = wp.media({
                    title: 'Choose Image',
                    button: {
                        text: 'Choose Image'
                    },
                    multiple: true
                });
                //When a file is selected, grab the URL and set it as the text field's value
                custom_uploader.on('select', function () {
                    console.log(custom_uploader.state().get('selection').toJSON());
                    attachment = custom_uploader.state().get('selection').first().toJSON();
                    
                    var thumbUrl = attachment && attachment.sizes && attachment.sizes.thumbnail && attachment.sizes.thumbnail.url
                    ? attachment.sizes.thumbnail.url
                    : attachment.url;
                    $('#wpb-category-image-preview').html('<img src=\"'+ thumbUrl +'\">');
                    $('#upload_image').val(attachment.id);
                });
                //Open the uploader dialog
                custom_uploader.open();
            });
        });";
    }
}

Next, you can scroll down to the ‘Insertion’ section and choose ‘Auto Insert’ to let the plugin handle placement for you.

Then, choose the ‘Insert Before Content’ option under the ‘Page, Post, Custom Post Type’ section in the ‘Location’ dropdown menu.

Select fallback image insertion option

You can then return to the top of the page and switch the toggle from ‘Inactive’ to ‘Active.’

Once you click the ‘Save Snippet’ button at the top, your fallback image will be in place.

Save and activate code snippet WPCode

You may also want to see our guide on how to add custom code snippets in WordPress.

Note: This code snippet will work only with the ‘category’ taxonomy. However, you can add more taxonomies by adding their name to the list in the following class in the code and changing the bracketed term to ‘tag’ or ‘post, for instance.

protected static $taxonomies = ['category'];

When you’re done, simply visit your website to see the fallback image.

Fallback image preview

We hope this article helped you add a fallback featured image based on the post category. You can also see our guide on how much it costs to build a website and the best email marketing services for small businesses.

If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.

Disclosure: Our content is reader-supported. This means if you click on some of our links, then we may earn a commission. See how WPBeginner is funded, why it matters, and how you can support us. Here's our editorial process.

Editorial Staff

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi with over 16 years of experience in WordPress, Web Hosting, eCommerce, SEO, and Marketing. Started in 2009, WPBeginner is now the largest free WordPress resource site in the industry and is often referred to as the Wikipedia for WordPress.

The Ultimate WordPress Toolkit

Get FREE access to our toolkit - a collection of WordPress related products and resources that every professional should have!

Reader Interactions

11 CommentsLeave a Reply

  1. Syed Balkhi says

    Hey WPBeginner readers,
    Did you know you can win exciting prizes by commenting on WPBeginner?
    Every month, our top blog commenters will win HUGE rewards, including premium WordPress plugin licenses and cash prizes.
    You can get more details about the contest from here.
    Start sharing your thoughts below to stand a chance to win!

  2. Nicola says

    Most interesting would to have a hook to replace thumbnail to be used in functions so not to bother replacing wherever the thumbnail is used

  3. Sohail says

    Thank you. This works like a charm :-)

    While the fallback featured image gets displayed in the post; any ideas on how could I display them in category/archive pages, or where the posts get displayed on the homepage?

  4. tina says

    Hello!
    Please show how the articles of the way they are displayed in the “MORE ON RIGHT NOW WPBEGINNER” above ?? a WordPress template
    Thank you

  5. David says

    I turned off the organize posts by date month in settings/media, and changed url to reflect uploads directory specifically – that way I can avoid the extra step. I’m hoping this won’t cause issues with my host but it certainly makes life a little easier for me. Thank you so much for sharing this info, I have been searching for a looooong time and it’s finally how I want it :)

  6. Rashid khan says

    hello,,, i want to add dynamic image on my wordpress home page. where al ready 5 images are set on differnet location..
    i just want to replace them and add new photo by post and catorrries…
    please help me
    i tried but no success
    i used post by thumbian function

  7. Richard Stewart says

    This is great, but I failed miserably trying to implement Displaying Category Image as Default Fallback Featured Image in my classifieds theme. It uses different categories from the ‘stock’ posts categories and the author refuses to help.

    Do you offer any technical services, paid or otherwise, where you can help me implement Displaying Category Image as Default Fallback Featured Image into my theme?

  8. Matt Cromwell says

    This is really awesome, a really useful tip in my case. Only issue is the first code above is incomplete. Luckily I didn’t need the “if” part, so I just pulled that out and all was well.

    Thanks for some pretty advanced tips on your “begginer’s” site. Keep it up!

  9. Damien Carbery says

    Another idea could to set the post thumbnail when the post is saved. The advantage of the solution above is that the category thumbnail is easily changed.

Leave a Reply to Sohail Cancel reply

Thanks for choosing to leave a comment. Please keep in mind that all comments are moderated according to our comment policy, and your email address will NOT be published. Please Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WPBeginner Assistant
How can I help you?

By chatting, you consent to this chat being stored according to our privacy policy and your email will be added to receive weekly WordPress tutorials from WPBeginner.