-
-
Save braddalton/ccc86aa192a8c93d66f1 to your computer and use it in GitHub Desktop.
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'); |
Try is_tax( $taxonomy, $term );
@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!
@nikkoboy The code for that is in one of these tutorials https://wpsites.net/tag/featured-image/
@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.
@nikkoboy Yes the code will work for any/all taxonomies and custom post types.
@braddalton Thanks a lot for pointing me in the right direction; I wasn't 100% sure that I had found the right tutorial.
@nikkoboy Here's the demo video showing what the code does https://www.youtube.com/watch?v=R7SL3l4SMYw
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!