我有一个称为product_category持有产品的自定义分类.如何通过子项列表获得顶级父项?
我知道如何使用get_terms()和传入'0'作为父级的顶级术语的全局列表,但我只想要它与当前存档页面相关的那个.
例:
杂志 -
格洛西
----时尚
书籍 -
硬皮
----冒险
如果我碰巧在时尚档案馆,我只想让杂志上有一份儿童用语,而不是书籍.
我想我明白了.我最终得到了以下内容:
$term_id = get_queried_object()->term_id; //Get ID of current term
$ancestors = get_ancestors( $term_id, 'product_category' ); // Get a list of ancestors
$ancestors = array_reverse($ancestors); //Reverse the array to put the top level ancestor first
$ancestors[0] ? $top_term_id = $ancestors[0] : $top_term_id = $term_id; //Check if there is an ancestor, else use id of current term
$term = get_term( $top_term_id, 'product_category' ); //Get the term
echo $term->name; // Echo name of top level ancestor
Run Code Online (Sandbox Code Playgroud)
也许有更好的方法来做到这一点,但这似乎工作正常.