As the post is saved, set the featured image based on the post category.
On a recent project the theme displays the featured image in the single post header area. Without a featured image the displayed post looks very plain. I wrote code to set the featured image as the post is saved.
Why do this automatically
I added this code because the displayed post would look very plain without a featured image. The site’s theme is quite minimal with lots of whitespace that makes images stand out. Their absence would also stand out, though not in a good way.
I also knew that the site owner is busy and may not have time to find an appropriate featured image as she writes a new post. By automatically adding a featured image the posts would look okay until she found a good image.
How it works
The code attaches to the ‘save_post‘ action. If the post doesn’t have a featured image the list of post categories are retrieved (the WordPress functions call it a “post thumbnail” because that was the name when it was first introduced in WordPress 2.9.0).
The handy wp_list_pluck() function extracts the slugs from the returned list. Code with slugs is much easier to maintain than using IDs.
The foreach loop goes through the post categories checking whether the category slug is in the the array of categories and featured images. If found it sets the post thumbnail and leaves the function.
The original project didn’t have an array of categories and featured images. Instead it set the featured image to an image used in the category. In that case wp_list_pluck() extracted the term_id and I then used get_term_meta() to get the ID of the category image.
Another option for this code is to set a default image if the post is not in any of the categories in the array of categories and featured images.