Wordpress,在归档页面获取当前分类等级

5
我将创建一个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输出恰当的值吗?

2个回答

7
尝试使用 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
}

0
我已经成功地让它像这样工作:
$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';
        }
    }
}

这不是最干净的解决方案,我知道。它可以正常工作,因为我的分类法子级数是有限的,但使用递归来回答会更好。也许有人仍然会发现这有帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接