如何获得与当前存档页面相关的顶级父术语?

时间:2013-07-08 20:53:58

标签: wordpress

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

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

示例:

杂志
--Glossy
----时尚
图书
--Hardcover
----惊险

如果我碰巧在时尚档案馆,我只想获得杂志,其中包含儿童术语列表,而不是书籍

3 个答案:

答案 0 :(得分: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

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

答案 1 :(得分:0)

我喜欢那个解决方案cbi。在制作自定义分层分类术语存档时,我无法相信我在获取此信息时遇到了这么大的困难。

答案 2 :(得分: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

?>