1

我有一个名为product_category保存产品的自定义分类法。如何获得带有子项列表的顶级父项?

get_terms()我知道如何使用并作为父项传入顶级术语的全局列表'0',但我只想要与当前存档页面相关的一个。

例子:

杂志
-- 光面书
----时尚
书籍
-- 精装书
----冒险

如果我碰巧在时尚档案中,我只想获得带有子术语列表的Magazines ,而不是Books

4

3 回答 3

5

我想我想通了。我最终得到以下结果:

$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

也许有更好的方法可以做到这一点,但这似乎工作正常。

于 2013-07-09T11:50:27.050 回答
0

我喜欢那个解决方案cbi。我不敢相信在制作自定义分层分类术语存档时,我很难获得这些信息。

于 2013-12-30T04:30:13.380 回答
0

<?php

  $terms = get_the_terms( $post->ID, 'categories' );
  if ( !empty( $terms ) ){
    // get the first term
    $term = array_shift( $terms );
    $term_id = $term->term_id;
  }

  $ancestors = get_ancestors( $term_id, 'categories' ); // 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, 'categories' ); //Get the term
  $top_term_id = $term->term_id;
  echo $top_term_id; // Echo name of top level ancestor

?>

于 2016-03-15T15:30:53.120 回答