0

Trying to display custom fields for categories on a category page.

  1. I added the fields to ACF in the category taxonomy
  2. Added this snippet into my custom category category-emails.php

    $image = get_field('header_image', 'category_74'); 
    echo($image); 
    

This works. It renders out the data I have in 'header_image'.

The problem is, category_74 is hardcoded into the template. So it will only show that header_image for category_74. Trying to make it so any category or sub category of category 74 has field 'header_image' available and that I wont have to modify the template.

Is there a way to write something more general, that replaces 'category_74' with something like 'categories'... I tried categories but didn't work.

4

Check this page out from the ACF docs: https://www.advancedcustomfields.com/resources/get-values-from-a-taxonomy-term/

Specifically this section:

"Finding the term related to the current post"

<?php

// load all 'category' terms for the post
$terms = get_the_terms( get_the_ID(), 'category');


// we will use the first term to load ACF data from
if( !empty($terms) ) {

    $term = array_pop($terms);

    $custom_field = get_field('header_image', $term );

    // do something with $custom_field
}

?>

I changed their "category_image" to your "header_image" value. I think that should work for you.

  • you are a genius. "Genius. Genius. Genius" that totally worked! – Tom May 26 '17 at 13:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.