如何获取自定义分类法的最底层术语?
分类层次结构示例,
Custom Taxonomy: “产品类别”
Top Level Terms -> Second Level Terms -> Third Level Terms -> Bottom most Level Terms
我只想得到Bottom most level taxonomy terms. 我想把这个从索引的循环中去掉。php页面,因此无法在get\\u terms()函数中设置父id。如何获取自定义分类法的最底层术语?
分类层次结构示例,
Custom Taxonomy: “产品类别”
Top Level Terms -> Second Level Terms -> Third Level Terms -> Bottom most Level Terms
我只想得到Bottom most level taxonomy terms. 我想把这个从索引的循环中去掉。php页面,因此无法在get\\u terms()函数中设置父id。这是我最终得到的解决方案。这也可以帮助其他人。
$taxonomy = "product-category";
$args = array(
\'taxonomy\' => $taxonomy,
\'orderby\' => \'name\',
\'order\' => \'ASC\',
\'hierarchical\' => true,
\'hide_empty\' => false,
);
$the_query = new WP_Term_Query($args);
$categories = $the_query->get_terms();
if ($categories){
foreach($categories as $category){
$ancestors = get_ancestors( $category->term_id, $taxonomy );
$category->ancestors = $ancestors;
$category->depth = count( $ancestors ) ;
if($category->depth === 3) :
echo $category->term_id . \'-\' . $category->depth . \'-\' . $category->name;
endif;
}
}
首先,我使用WP_Term_Query 类创建terms对象并构建自定义查询,然后get_terms() 检索所有术语。使用的内部foreach循环get_ancestors() 函数返回包含给定对象的父对象的数组$category->depth 获取当前深度。
情况是这样的;我正在使用get\\u terms从中检索所有术语Tax 1 与之关联的帖子。使用以下各项$args = array( \'hide_empty\' => 0, \'orderby\' => \'name\', \'taxonomy\' => \'tax_1\' ); $terms = get_te