Wordpress:仅显示二级分类术语

Wordpress: Display only 2nd level taxonomy terms

我有一个自定义 post 类型的 'stories'。我有 'story_categories' 的分类法。我需要显示顶级类别,并在这些类别之下显示子类别。它适用于以下代码...

<?php
    $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 ); ?>
</ul>

...直到我单击其中一个子类别。然后我得到 'No categories'(我假设这是因为它一直在寻找 current 页面的子类别,并且该子类别有 none 个)。

有没有一种方法可以使上面的代码始终显示某个级别的子类别,即使我在子类别中?例如:

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)

谢谢

问题是因为您要通过 child_of 当前学期。要修复它,只需检索当前术语的根父级即可。

选项 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);

然后,一旦您检索到根目录,就可以像这样更新您的参数:

'child_of' => $root->term_id

选项 2

不想循环的话可以用get_ancestors:

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

然后传递最后一个元素:

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