Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Add Default Featured Image For Each Post In A Category http://wpsites.net/web-design/add-default-featured-image-for-each-post-in-a-category/
function default_category_featured_image() {
global $post;
$featured_image_exists = has_post_thumbnail($post->ID);
if (!$featured_image_exists) {
$attached_image = get_children( "post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=1" );
if ($attached_image) {
foreach ($attached_image as $attachment_id => $attachment) {
set_post_thumbnail($post->ID, $attachment);
}}
else if ( in_category('54') ) {
set_post_thumbnail($post->ID, '40380');
}
else if ( in_category('55') ) {
set_post_thumbnail($post->ID, '40383');
}
else if ( in_category('56') ) {
set_post_thumbnail($post->ID, '40382');
}
else {
set_post_thumbnail($post->ID, '40381');
wp_reset_postdata();
}
}
}
add_action('the_post', 'default_category_featured_image');
@Garconis
Copy link

Garconis commented Aug 18, 2017

Thoughts on how to change this from in_category to use a taxonomy tag instead? Also, is there an easy way to say "if it's in more than one of those tag, use THIS image instead of the one previously defined"? Thanks!

@braddalton
Copy link
Author

braddalton commented Sep 3, 2018

Try is_tax( $taxonomy, $term );

@nikkoboy
Copy link

nikkoboy commented Jun 15, 2021

@braddalton that's a super helpful code snippet!
I would like to tweak it so it forces to display a default featured image, EVEN if a post already has a featured image. Basically, I want to override ALL featured images site-wide and replace them ALL by default category images. How could this be achieved? Thanks!

@braddalton
Copy link
Author

braddalton commented Jun 15, 2021

@nikkoboy The code for that is in one of these tutorials https://wpsites.net/tag/featured-image/

@nikkoboy
Copy link

nikkoboy commented Jun 15, 2021

@braddalton, thanks a lot! I'll have a look at it right away. Does the code also work for other types of taxonomies like for instance WP Job Manager's? They use job_listing_category instead of in_category.

@braddalton
Copy link
Author

braddalton commented Jun 16, 2021

@nikkoboy Yes the code will work for any/all taxonomies and custom post types.

@nikkoboy
Copy link

nikkoboy commented Jun 17, 2021

@braddalton Thanks a lot for pointing me in the right direction; I wasn't 100% sure that I had found the right tutorial.

@braddalton
Copy link
Author

braddalton commented Jun 17, 2021

@nikkoboy Here's the demo video showing what the code does https://www.youtube.com/watch?v=R7SL3l4SMYw

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment