Support

Account

Home Forums Front-end Issues Displaying Fields from Post Category or Subcategory

Solved

Displaying Fields from Post Category or Subcategory

  • I have custom fields setup and displaying in the admin on my post categories and sub-categories.

    I’m using this output in my child-category.php

    <?php 
    the_field('test_field');
    ?>

    When viewing the category page, nothing displays.

  • You’ll need to set the second function parameter to ‘category-slug_2’ where ‘2’ is the term ID. So for example:

    
    the_field('test_field', 'beer_' . $term_id);
    

    would output the “test_field” value for the term with ID $term_id in the “beer” taxonomy.

  • Thanks for your quick reply. There’s probably something I’m not understanding about $term_id. I have a regular WP post category of “stories-by-state” which has subcategories of each state (alabama, alaska, etc.). I don’t think the fact that I’m retrieving subcategory info has any effect on the outcome.

    Given your instruction, I would have something like the folowing:

    the_field('test_field', 'alabama_' . $term_id);

    or

    the_field('test_field', 'alabama_16');

    where 16 is the the number I get from the ur:l /wp-admin/edit-tags.php?action=edit&taxonomy=category&tag_ID=16&post_type=post

    Neither worked and I”m not 100% sure how to pull $term_id.

  • Hi @JCIDEV

    The $post_id parameter needs to be the $taxonomyName + $termID.

    Your taxonomyName is actually ‘category’, not ‘alabama’ (alabama is your term name)

    Modify your code to:

    
    the_field('test_field', 'category_' . $term_id);
    

    and that should work

  • Ah, that did it! THANK YOU!

    Here was my final code that actually got the current category ID for me:

    $current_category = single_cat_title("", false);
    $term_id = get_queried_object_id($current_category);
    the_field('test_field', 'category_' . $term_id);

    I’m sure there’s a more efficient way.

    Thank you again!

  • My real-world application needed repeater fields, so here are repeater fields from a category page:

    $current_category = single_cat_title("", false);
    $term_id = get_queried_object_id($current_category);
    
    if(get_field('state_links', 'category_' . $term_id))
    {
    echo '<h2><span>';
    echo single_cat_title() . ' FFA Links';
    echo '</span></h2>';
    echo '<ul id="double" class="state">';
    while(has_sub_field('state_links', 'category_' . $term_id))
      {
        echo '<li class="state"><a href="' . get_sub_field('state_link', 'category_' . $term_id) . '" target="_blank">' . get_sub_field('state_link_title', 'category_' . $term_id) . '</a></li>';
      }
      echo '</ul>';
    }
Viewing 7 posts - 1 through 7 (of 7 total)

The topic ‘Displaying Fields from Post Category or Subcategory’ is closed to new replies.