我正在创建一个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';
}
}
}
我知道,这不是最干净的解决方案。它工作正常,因为我有一个有限数量的分类子级别,但看到它使用递归来回答会很好。也许有人觉得这很有帮助。