仅回应当前类别的子/子类别

时间:2016-10-24 作者:Dan Bruce

我试图只回显当前类别的所有子/子类别。这是我的代码,但它显示所有子类别,无论我们在哪个父类别上。我只需要在自定义分类法中显示父类别的子类别。

我尝试过改变这一点:

\'parent\' => 0, 
没有运气。

<?php
    $taxonomyName = "cosmetics";
    $parent_terms = get_terms($taxonomyName, array(\'parent\' => 0, \'orderby\' => \'slug\', \'hide_empty\' => false));   
    echo \'<div style="height: 200px; text-transform: uppercase; border:1px solid #666666; padding:10px; overflow-y: scroll;">
    <div class="breaker-small">Refine Search</div>\';
    foreach ($parent_terms as $pterm) {
        $terms = get_terms($taxonomyName, array(\'parent\' => $pterm->term_id, \'orderby\' => \'slug\', \'hide_empty\' => false));
        foreach ($terms as $term) {
            echo \'<p class="filters"><a href="\' . get_term_link( $term->name, $taxonomyName ) . \'">\' . $term->name . \'</a></p>\';  
        }
    }
    echo \'</div>
    <br />\';

    ?> 
非常感谢!

1 个回复
最合适的回答,由SO网友:TheDeadMedic 整理而成

您的代码循环遍历所有顶级类别,然后显示每个类别的所有子类别,所以我对它显示所有子类别并不感到惊讶!

如果要显示当前类别的子术语(即,在类别存档中?),使用:

$current_cat_id = get_queried_object_id();
$kids = get_terms([
    \'taxonomy\' => get_queried_object()->taxonomy,
    \'parent\'   => $current_cat_id,
]);
作为一个完整的答案:

<?php

$terms = get_terms([
    \'taxonomy\' => get_queried_object()->taxonomy,
    \'parent\'   => get_queried_object_id(),
]);

echo \'<div style="height: 200px; text-transform: uppercase; border:1px solid #666666; padding:10px; overflow-y: scroll;">
<div class="breaker-small">Refine Search</div>\';
foreach ( $terms as $term) {
    echo \'<p class="filters"><a href="\' . get_term_link( $term ) . \'">\' . $term->name . \'</a></p>\';  
}
echo \'</div>
<br />\';

?>