Last active
June 30, 2022 15:40
-
-
Save braddalton/ccc86aa192a8c93d66f1 to your computer and use it in GitHub Desktop.
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/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'); |
@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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@nikkoboy The code for that is in one of these tutorials https://wpsites.net/tag/featured-image/