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 How to set fallback featured image based on post category in WordPress](https://www.wpbeginner.com/wp-content/uploads/2013/12/how-to-set-fallback-featured-image-based-on-post-category-in-wordpress.png)
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 Enable taxonomy images for category](https://www.wpbeginner.com/wp-content/uploads/2013/12/enable-taxonomy-images-for-category.png)
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 New image field for categories](https://www.wpbeginner.com/wp-content/uploads/2013/12/new-image-field-for-categories.png)
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.
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 Upload images to media library](https://www.wpbeginner.com/wp-content/uploads/2013/12/upload-images-to-media-library.png)
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 Uploads folder in WordPress](https://www.wpbeginner.com/wp-content/uploads/2016/03/uploads-folder.jpg)
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 Media uploads organized in year and monthly folders](https://www.wpbeginner.com/wp-content/uploads/2016/03/media-uploads.jpg)
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 Click 'Add New Snippet' in WPCode](https://www.wpbeginner.com/wp-content/uploads/2011/09/wpcode-add-new-snippet.png)
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 with new snippet Add custom code in WPCode](https://www.wpbeginner.com/wp-content/uploads/2011/09/add-custom-code-new-snippet.png)
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.
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 Select fallback image insertion option](https://www.wpbeginner.com/wp-content/uploads/2013/12/select-fallback-image-insertion-option.png)
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.
![Activate and save code snippet WPCode Save and activate code snippet WPCode](https://www.wpbeginner.com/wp-content/uploads/2011/09/save-snippet-wpcode.png)
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.
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.
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!
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
Sohail says
Thank you. This works like a charm![:-)](https://www.wpbeginner.com/wp-content/plugins/classic-smilies/img/icon_smile.gif)
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?
Deepak says
do we now have a plugin for this same requirement? or we need to still use manual method?
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
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![:)](https://www.wpbeginner.com/wp-content/plugins/classic-smilies/img/icon_smile.gif)
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
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?
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!
WPBeginner Support says
@Matt thanks for notifying us, we have fixed it.
Admin
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.