Wordpress: Display only 2nd level taxonomy terms

I have a custom post type of 'stories'. I have a taxonomy of 'story_categories'. I need to display the top level categories, and below these the child categories. It works fine with the following code...

    $queried_object = get_queried_object();
    $term_id = $queried_object->term_id;
    $list_child_terms_args = array(
        'taxonomy' => 'story_categories',
        'title_li' => '',
        'child_of' => $term_id
<ul class="list list-links list-links-small">
    <?php wp_list_categories( $list_child_terms_args ); ?>

...up until I click one of the subcategories. Then I get 'No categories' (I assume this is because it's always looking for the subcategories of the current page, and the subcategory has none of these).

Is there a way to use the above code in a way where it always displays the subcategories of a certain level, even if I'm in a subcategory? eg:

Stories (top level)
--News (2nd level) < Always display subcats of this at all times
--Events (2nd level) < Always display subcats of this at all times
---Stuff (3rd level)
---Stuff (3rd level)


1 answer

  • answered 2018-02-13 02:20 Chin Leung

    The problem is because you're passing child_of the current term. To fix it, simply retrieve the root parent of your current term.

    Option 1

    // Loop until you reach the top parent term
    $root = $queried_object;
    while($root->parent != '0')
        $root = get_term_by('id', $root->parent, $root->taxonomy);

    Then once you've retrieve the root, update your args like this:

    'child_of' => $root->term_id

    Option 2

    If you don't want to loop, you can use get_ancestors:

    $parents = get_ancestors($term_id, $queried_object->taxonomy, 'taxonomy');

    Then pass the last element:

    'child_of' => $parents ? end($parents) : $term_id