最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

ACF add custom fields to categories and display

programmeradmin1浏览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.

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.

Share Improve this question edited Mar 18, 2019 at 13:27 fuxia 107k39 gold badges255 silver badges459 bronze badges asked May 26, 2017 at 13:13 TomTom 2351 gold badge2 silver badges8 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 7

Check this page out from the ACF docs: https://www.advancedcustomfields/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.

发布评论

评论列表(0)

  1. 暂无评论