Answers:
感谢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;
}
这是一个简单的函数,它将为您提供任何给定术语中最顶级的父术语:
function get_term_top_most_parent( $term_id, $taxonomy ) {
$parent = get_term_by( 'id', $term_id, $taxonomy );
while ( $parent->parent != 0 ){
$parent = get_term_by( 'id', $parent->parent, $taxonomy );
}
return $parent;
}
一旦有了此功能,您就可以循环遍历由wp_get_object_terms
以下命令返回的结果:
$terms = wp_get_object_terms( $post->ID, 'taxonomy' );
$top_parent_terms = array();
foreach ( $terms as $term ) {
//Get top level parent
$top_parent = get_term_top_most_parent( $term->ID, 'taxomony' );
//Check if you have it in your array to only add it once
if ( !in_array( $top_parent->ID, $top_parent_terms ) ) {
$top_parent_terms[] = $top_parent;
}
}
我遇到了同样的问题,并且很容易解决。看一下这个:
定义$taxonomy
。它可能是您想要获取数据的分类法的一个标头。完成此操作后,您可以简单地执行以下操作:
<?php
$postterms = wp_get_post_terms($post->ID, $taxonomy); // get post terms
$parentId = $postterms[0]->parent; // get parent term ID
$parentObj = get_term_by('id', $parentId, $taxonomy); // get parent object
?>
现在您得到的是这样的:
object(stdClass)#98 (11) {
["term_id"]=>
int(3)
["name"]=>
string(8) "Esportes"
["slug"]=>
string(8) "esportes"
["term_group"]=>
int(0)
["term_taxonomy_id"]=>
int(3)
["taxonomy"]=>
string(17) "noticiaseditorias"
["description"]=>
string(0) ""
["parent"]=>
int(0)
["count"]=>
int(4)
["object_id"]=>
int(123)
["filter"]=>
string(3) "raw"
}
您可以使用它$parentObj
来获取子弹,名称,ID等。只是通过使用$parentObj->slug
或$parentObj->name
作为示例。
也许这会有所帮助: get_ancestors( $object_id, $object_type );