Set A Featured Image Based On What Term(s) Are Added To A Post

WordPress

If you can’t find a decent plugin to handle setting a featured image based on what terms are added to a post, you can accomplish this using a function.

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).

For example, if you have your posts have a custom taxonomy of “Job Type,” you can set a featured image for each of the Job Types (e.g., Assistant, Chefs, etc.).

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');

This only works for NEW posts, or posts that don’t yet have a featured image set.

The nice thing about using this function is you can also specify what featured image to assign if there are NO terms. Same with if there are MULTIPLE terms.

Note: the numbers in the set_post_thumbnail part is the ID of the media item. You can find that ID by going to the Media Library and clicking the image. You’ll grab the number at the end of upload.php?item=

You’ll also of course need to update the “jobtype” to match whatever your taxonomy slug is. Same with the other slugs of your actual terms.

Menu
Google Rating
5.0
Get a Quote