Support

Account

Home Forums General Issues Show taxonomy image on custom post

Helping

Show taxonomy image on custom post

  • I am trying to show a custom image on certain post based on the category. I have made my location rule to “Show this field group if taxonomy term = custom-category” . Now I can go to those categories and add a photo to the ones I need to. I made an image field that returns the value “Image URL” I am trying to display those images now based on the post. So for example I add a photo of a green circle to the category “circle”. I want to now display that photo of a green circle on any post that has the category “circle”. I have spent hours on stack overflow and the taxonomy documentation. I am stuck and any help is appreciated.

  • The first thing that you need to do is to get the terms that the post is in.

    
    $post_id = $post->ID;
    $taxonomy = 'custom-category';
    $args = array('fields' => 'ids');
    $terms = get_post_terms($post_id, $taxonomy, $args);
    

    $terms will hold an array term ids that the post is in. For more information on this see https://codex.wordpress.org/Function_Reference/wp_get_post_terms

    Once you have a list of terms you can get the images from those terms. In the below I am using “image_field” for the name of your image field.

    
    for (i=0; i<count($terms), i++) {
        $term_post_id = $taxonomy.'_'.$terms[i];
        $image_url = get_field('image_field', $term_post_id);
        if ($image_url) {
            // your code for showing the image here
        }
    }
    

    For more about getting values in acf from things like taxonomy terms see the Get a value from other places section on this page: http://www.advancedcustomfields.com/resources/get_field/

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

The topic ‘Show taxonomy image on custom post’ is closed to new replies.