Add an Image to a Category to show in both Category and Post Templates in WordPress

You can add an image to a Category 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


// 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 the 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.



Leave a Comment

%d bloggers like this: