在本演示中,我们假设我们有一个名为;书籍;。我们可能有一个层次结构:
Fiction (id: 699)
- This is a Fiction Story.
Non-Fiction
- Title of Non-fiction
Fantasy
- ...
我们想得到分类法的父术语;书籍“;当前职位的。
/* Get the Parent Taxonomy Term Name by post Id */
function get_parent_term_by_post_id($taxname, $taxid=null){
if(isset($taxid)):
//Get by term Id passed in function
$parent_tax = get_term_by(\'id\', $taxid, $taxname);
return $parent_tax ->name; //use name, slug, or id
else:
//Get by PostId of current page
$terms = wp_get_post_terms( get_the_id(), $taxname);
$tax_parent_id = $terms[0]->parent;
if($tax_parent_id == 0):
$tax_parent_id = $terms[0]->parent; //get the next parent ID
endif;
$parent_tax = get_term_by(\'id\', $tax_parent_id , $taxname);
return $parent_tax ->name; //use name, slug, or id
endif;
}
然后在模板上运行,如下所示:
//enter custom tax name. will grab by post id
echo get_parent_term_name_by_post_id(\'books\'); //returns Fiction
或
//by term ID
echo get_parent_term_name_by_post_id(\'books\', 699); //returns Fiction