Last active
August 30, 2017 22:14
-
-
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).
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
<?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