How to display a value inside a post with a specified category from a category custom field?

I added a custom field to category using ACF,
something like this:

How to display a value inside a post with a specified category from a category custom field?

so that I can specify a value for each category (like an image or text).
How can I call for or display this or these values inside every post with the specified category.
How do I write the code inside single.php?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can use get_the_category() to get the categories assigned to a specific post and use the_field() or get_field() to display/get the value of a specific ACF field. (You can also use get_term_meta() in place of get_field())

So for example, the following will display a simple list of the categories (and I really mean plain simple), with the custom Image and Color fields next after the category name. Note that this assumes your Image field was set to return an image attachment’s ID.

$cats = get_the_category();
if ( ! empty( $cats ) ) {
    echo '<ul>';

    foreach ( $cats as $term ) {
        echo '<li>';

        echo $term->name;

        $selector = 'category_' . $term->term_id;

        // Display the category image.
        $att_id = get_field( 'image', $selector );
//      $att_id = get_term_meta( $term->term_id, 'image', true );
        echo wp_get_attachment_image( $att_id );

        // Display the category color.
        the_field( 'color', $selector );
//      echo get_term_meta( $term->term_id, 'color', true );

        echo '</li>';
    }

    echo '</ul>';
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x