感谢Ivaylo提供的这段代码,它是基于Bainternet的答案。
下面的第一个函数,get_term_top_most_parent
, 接受术语和分类法,并返回术语的顶级父级(或术语本身,如果它是无父级的);第二个功能(get_top_parents
) 在循环中工作,并且在给定分类的情况下,返回一个帖子术语顶级父级的HTML列表。
// Determine the top-most parent of a term
function get_term_top_most_parent( $term, $taxonomy ) {
// Start from the current term
$parent = get_term( $term, $taxonomy );
// Climb up the hierarchy until we reach a term with parent = \'0\'
while ( $parent->parent != \'0\' ) {
$term_id = $parent->parent;
$parent = get_term( $term_id, $taxonomy);
}
return $parent;
}
拥有上述函数后,可以循环返回的结果
wp_get_object_terms
并显示每个术语的顶级父项:
function get_top_parents( $taxonomy ) {
// get terms for current post
$terms = wp_get_object_terms( get_the_ID(), $taxonomy );
$top_parent_terms = array();
foreach ( $terms as $term ) {
//get top level parent
$top_parent = get_term_top_most_parent( $term, $taxonomy );
//check if you have it in your array to only add it once
if ( !in_array( $top_parent, $top_parent_terms ) ) {
$top_parent_terms[] = $top_parent;
}
}
// build output (the HTML is up to you)
$output = \'<ul>\';
foreach ( $top_parent_terms as $term ) {
//Add every term
$output .= \'<li><a href="\'. get_term_link( $term ) . \'">\' . $term->name . \'</a></li>\';
}
$output .= \'</ul>\';
return $output;
}