I hate not being able to find a good image for the featured image. Most of the posts I write are tutorials with code snippets, not images. As a result, many of my posts can easily not have featured images. Unfortunately, though, that would (and did) cause an inconsistent flow on my post index pages (main blog page, tags, categories, etc.); some posts had images and others didn’t.
As I’ve continued to add more posts over time, this has started to bother me more and more. I decided to try to come up with a way to set a default image for my posts when I don’t set one myself. Additionally, I wanted to set different featured images depending on a post’s category. After searching, I found a few different tutorials on setting default images for WordPress posts. I tried some of those suggestions but had mixed results and none of them worked 100%.
Since I use Genesis, I could have just added the images using a Genesis hook but this doesn’t actually set the image to the featured image. Unfortunately, this would not work for me because I wanted to keep the functionality of my Twitter card (Summary Card with Large Image), which shows the featured image of a post when the link is shared. Therefore, my only option was to make sure that a featured image was set.
Default Featured Images
After not much luck and wasting time with existing snippets, I decided to look at the Default Featured Image plugin from the WordPress repo. It seemed to work for setting a general featured image so I took a look at the code and found a filter that intrigued me enough to download and test.
Once you install and activate the Default Featured Image plugin, it adds a setting under Settings → Media. This setting will let you select a default featured image for all of your posts (including ones already published) when no featured image is set manually. This is the extent of the plugin’s admin settings so there’s nothing else to mess with in the dashboard. The plugin goes to work once you choose your image.
Conditional Featured Images
Once I got my default featured image set, I wanted to test the filter I referred to above. This filter,
dfi_thumbnail_id, appeared to make possible dynamic featured images. I wrote a bit of code and tested it out. Success! This filter did exactly what I had hoped.
I definitely found a new plugin that I really like in Default Featured Image. If you want an easy way to set a general default featured image for your posts, it gives you exactly that. If you also want flexibility in controlling which image is used as a post’s featured image (conditional featured images), here’s a simplified version of the code I wrote for it.
In this sample code, you’re assigning a post’s featured image to a media upload with the ID of 3020 if the post has the category of “tutorials”, 3019 if “reviews” and 3018 if “lists”. You can get as granular with this as you need to.
I hope this post has helped you! If you have questions, leave them below.