Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
WordPress | Set a default featured image (post thumbnail) to each post, based on the term (e.g., Tag) that is assigned to the post. Essentially this sets a featured image for the custom terms you specify (of a specified custom taxonomy).
<?php
function default_category_featured_image() {
global $post;
$featured_image_exists = has_post_thumbnail($post->ID);
$terms = get_the_terms($post->ID, 'jobtype');
$number = sizeof ($terms);
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);
}
}
// if multiple terms
else if ( $number > 1 ) {
set_post_thumbnail($post->ID, '4650');
}
// assistant
else if ( has_term( 'assistant', 'jobtype' ) ) {
set_post_thumbnail($post->ID, '2573');
}
// chefs
else if ( has_term( 'chefs', 'jobtype' ) ) {
set_post_thumbnail($post->ID, '2571');
}
// childcare
else if ( has_term( 'childcare', 'jobtype' ) ) {
set_post_thumbnail($post->ID, '2572');
}
// IF NO TERMS
else {
set_post_thumbnail($post->ID, '4650');
wp_reset_postdata();
}
}
}
add_action('the_post', 'default_category_featured_image');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment