在存档页面中获取当前级别的分类法


Wordpress, get current level of taxonomy in an archive page

我正在创建一个WordPress站点,使用自定义帖子类型和自定义分层分类法来显示项目目录。我希望保持简单,并在单个存档页面中处理项目,但是我需要帮助来确定当前显示的分类法级别。基本上,我需要以下功能:

if ($current_term_level = 0) {
    // show first drop-down
} else if ($current_term_level = 1) {
    // show second drop-down
} else {
    // show third drop-down
}

有人能解释一下如何让$current_term_level输出适当的值吗?

尝试使用get_ancestors()的WP功能:

function get_tax_level($id, $tax){
    $ancestors = get_ancestors($id, $tax);
    return count($ancestors)+1;
}
$current_term_level = get_tax_level(get_queried_object()->term_id, get_queried_object()->taxonomy);
if ($current_term_level = 0) {
    // show first drop-down
} else if ($current_term_level = 1) {
    // show second drop-down
} else {
    // show third drop-down
}

我已经设法使它像这样工作:

$current_term = get_queried_object()->slug;
$tax_name = 'items';
$terms = get_terms( $tax_name );
foreach($terms as $term) {
    $parent = get_term($term->parent, $tax_name);
    $grandparent = get_term($parent->parent, $tax_name);
    $great_grandparent = get_term($grandparent->parent, $tax_name);
    if ($term->slug == $current_term) {
        if ($term->parent == 0) {
            echo 'top level';
        } else if ($parent->parent == 0) {
            echo 'second level';
        } else if ($grandparent->parent == 0) {
            echo 'third level';
        } else if ($great_grandparent->parent == 0) {
            echo 'fourth level';
        }
    }
}
我知道这不是最干净的解决方案。它工作得很好,因为我有有限数量的分类法子级别,但是使用递归来回答它会很好。也许有人觉得这很有帮助。