In this tutorial, i’ll provide the code which sets a default post thumbnail/featured image for all posts in each category. This means all posts which don’t include a featured image, will automatically include the same featured image for that category.
First step is to create a default featured image for each category and upload them using the native Media library in WordPress.
You will then need to find the i.d for each category and the attachment i.d for each image.
Here’s an example:
Permalink: http://example.com/wordpress/?attachment_id=40380 category i.d 22
Permalink: http://example.com/wordpress/?attachment_id=40383 category i.d 23
Permalink: http://example.com/wordpress/?attachment_id=40382 category i.d 24
Each permalink can be viewed by going to Media > Library > Edit Image. Here’s a screenshot:
You can clearly see one category featured image which has been uploaded to the Media Library and the permalink for this image.
At the end of the permalink you can see the attachment i.d for this image which needs to be added to the code below along with the category i.d you want the image to display as your default category featured image.
Once you have all the i.d’s, you can then replace them in this code which needs to be added to the end of your child themes functions.php file.
You can add more else if statements to this code if you know what you’re doing.
The code also includes a default featured image which is set for all other posts not in the categories listed in the code. You can remove these 2 lines of code if you don’t want a global default featured image set for posts which you haven’t added a featured image:
else if ( in_category('56') ) {
set_post_thumbnail($post->ID, '40382');
}
Leave a Reply
You must be logged in to post a comment.