基于this answer, 以下是我的函数,用于获取数组中的所有术语:
function get_term_ancestors($post_id, $taxonomy){
// Declare the array where we are going to store the terms
$ancestors = array();
// start from the current term
$parent = array_shift(get_the_terms($post_id,$taxonomy));
// climb up the hierarchy until we reach a term with parent = \'0\'
while ($parent->parent != \'0\'){
$term_id = $parent->parent;
$parent = get_term_by( \'id\', $term_id, $taxonomy);
$ancestors[] = $parent;
}
return $ancestors;
}
使用方法如下:
$ancestors = get_term_ancestors(123,\'product_cat\');
因此,使用此函数,您的顶级术语将是:
$ancestors[count($ancestors)-1] // or array_pop($ancestors);
你的第二位顶级家长
$ancestors[count($ancestors)-2] // or another array_pop($ancestors)
请注意,在尝试访问isset($祖先[计数($祖先)-2])之前,您应该先检查它
Warning : 这只适用于一个期限内的产品。此函数不处理多个术语