Support

Account

Home Forums General Issues Show Taxonomy Image on Posts

Solving

Show Taxonomy Image on Posts

  • Hi,

    I have created an image for taxonomies category tag and output it in the archive.php template with..

    <?php
    
    // get the current taxonomy term
    $term = get_queried_object();
    
    // vars
    $image = get_field('jg_category_tag', $term);
    
    ?>
    <div class="fl-archive container">
    <img src="<?php echo $image['url']; ?>" />
    </div>

    I would like to output this image also on any single posts that are linked to the category – how can I achieve this?

    Thanks in advance.

  • So I worked out out to show the Taxonomy image in a single or archive template of a post that belongs to the category..

    $image = get_field('jg_category_tag', 'category_5');
    
        if ( in_category( 'my-category' ) ) {
            echo '<img src="' . $image['url'] . '" /> ';
    }

    So i use a conditional check to see if the post belongs to the category and if it does it displays the category image.

    But now what is the more optimal way of writing the code when I have numerous categories with images and to only display when a post belongs to them.

    The code below would go into the loop but is not efficient…

    // vars
    $image = get_field('jg_category_tag', 'category_5');
    $image7 = get_field('jg_category_tag', 'category_7');
    $image8 = get_field('jg_category_tag', 'category_8');
    
    if ( in_category( 'my-category' ) ) {
        echo '<img src="' . $image['url'] . '" /> ';
     }
    if ( in_category( 'your-category' ) ) {
        echo '<img src="' . $image7['url'] . '" /> ';
    }
    if ( in_category( 'another-category' ) ) {
        echo '<img src="' . $image8['url'] . '" /> ';
    }
    
  • Think I have worked this out using a foreach loop from get_terms and then test to see if the post is in the category still with in_category

    $types = get_terms( array(
        'taxonomy' => 'category',
        'hide_empty' => true,
    ) );
    
    foreach($types as $type) {
        
        $image = get_field('jg_category_tag', 'category_' . $type->term_id . '' );
        
        if( in_category($type->term_id )) {
            echo '<img src="' . $image['url'] . '" /> ';
        }
    }

    Now the posts in the loop will display the categories images only if they belong to the category.

Viewing 3 posts - 1 through 3 (of 3 total)

The topic ‘Show Taxonomy Image on Posts’ is closed to new replies.