Add and Show Featured Images in Taxonomy Templates and in Single and Archive Posts
You can add a featured image to a Category Taxonomy in WordPress by using ACF and selecting the categories taxonomy, so now a new image field appears in the category back end page, the same process can be applied to other taxonomy templates such as custom taxonomies.
Create a ACF Image Field for Taxonomy
Create a new custom image field
Assign the field to the relevant taxonomy, category in this case, you can also see other Taxonomies present.
Now you can upload an image directly on the category page.
Output the Image on the Category Page
Now you need to edit the template for outputting the image, this can be either very specific to the category, like category-{id}.php or more generic like archive.php
<?php // get the current taxonomy term $term = get_queried_object(); // vars $image = get_field('cat_image', $term); ?> <img src="<?php echo $image['url']; ?>" />
Output the Category Images on Single & Archive Pages
You can then further display the category images on a single post or blog archive page by using a foreach loop on the categories and output the image only if at least a post is linked to that category.
$types = get_terms( array( 'taxonomy' => 'category', 'hide_empty' => true, ) ); foreach($types as $type) { $image = get_field('cat_image', 'category_' . $type->term_id . '' ); if( in_category($type->term_id )) { echo '<img src="' . $image['url'] . '" /> '; } }
So using get_terms with a taxonomy value set to categories and hiding empty categories if not used start a foreach loop to run through the categories.
The ACF image field is set to the custom field name and category_ID.
The post is checked if it appears in each category iteration, and if so outputs the image.
Using a Custom Taxonomy
If you were using a custom taxonomy you can use the has_term function to check if the taxonomy is used by the post in the loop.
$types = get_terms( array( 'taxonomy' => 'tribe_events_cat', 'hide_empty' => true, ) ); foreach($types as $type) { $image = get_field('cat_image', 'tribe_events_cat_' . $type->term_id . '' ); if ( has_term( $type->term_id, 'tribe_events_cat')) { echo '<img src="' . $image['url'] . '" /> '; } }
So in the above the Modern Tribe Event Calendar taxonomy is used tribe_events_cat and defined in the initial get_terms array, it is further used in the $image variable just changing the taxonomy name. Then has_term is used to check if the post in the loop is tagged to the taxonomy has_term( $type->term_id, ‘tribe_events_cat’) and if it is, the image is output.