WordPress:通过术语ID获取顶级分类法



我有一个自定义分类法的ID。现在我尝试获得该ID的顶级分类。

例如,这是我的分类树:

  • 汽车(ID:1(
    • 梅赛德斯(ID:2(
      • S级(ID:3(

我试图在ID3的基础上从第一级(ID:1(获取ID。

我发现了很多例子,但它们不适用于只有一个给定的整数/ID。

例如这个:

function get_term_top_most_parent( $term_id, $taxonomy ) {
$parent  = get_term_by( 'id', $term_id, $taxonomy );
while ( $parent->parent != 0 ){
$parent  = get_term_by( 'id', $parent->parent, $taxonomy );
}
return $parent;
}

我用3更改了$term_id,但它没有任何作用。

经过一些测试,我在这里找到了一个很好的答案。

我的代码现在看起来是这样的:

$tax_ancestors = get_ancestors( $tax_first_id, 'product_cat' ); // $tax_first_id = 3
if ( !empty($tax_ancestors)) : 
$tax_last_id = end($tax_ancestors);
else :
$tax_last_id = $tax_first_id;
endif;

最新更新