Skip to content

Instantly share code, notes, and snippets.

@Garconis
Last active August 30, 2017 22:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Garconis/14770e7402e86d362bb6709c12f5d32c to your computer and use it in GitHub Desktop.
Save Garconis/14770e7402e86d362bb6709c12f5d32c to your computer and use it in GitHub Desktop.
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