是的,你可以。这里帮助您的功能是get_term()
. 此函数的返回为您提供了parent
. 使用此ID,您可以获得父分类法(只要它与类别一样具有层次结构)。
注意
要使此功能正常工作,您必须只为您的帖子选择最下面的类别,例如“南苏丹”。如果还选择了父类别,则函数无法知道要使用哪一个类别(或者只是需要更多的处理)。
如果使用多个类别,同样的问题也会出现——要么得到多个面包屑的输出,要么只有一个,可能是错误的。
单个底部类别的脚本可能是这样的,并且应该告诉您需要做什么:
更新我增强了脚本的功能,以确保多类别兼容性。它现在搜索所有设置的类别,找到类别祖先最多的类别,并打印出包含所有类别链接的面包屑。
$seperator = \' | \'; // Change to whatever you need
$categories = get_the_category( get_the_ID() ); // get the categories for your post
// check if categories are set
if ( is_array( $categories ) && count( $categories ) > 0 ) {
$mostancestors = 0; //controlvariable
$foundcategory; //save the category
// Loop through the categories
foreach( $categories as $thiscategory ) {
//check how many ancestors the current category has
$thisancestors = howManyAncestors( $thiscategory );
// if more than the previous record holder
if ( $thisancestors > $mostancestors ) {
$mostancestors = $thisancestors; //increase the controlvariable to the Amount calculated
$foundcategory = $thiscategory; //Set the found category to the one with more ancestors
}
}
// get the parent of the found category
$parent = get_term( $foundcategory->parent, \'category\' );
// loop to the next parent as long as it is different than the current one and exists
while ( $parent->term_id != $foundcategory->term_id && !is_wp_error( $parent ) && $parent->term_id != 0 ) {
// Add the Link for each parent in front of the existing Links
$categorylinks = \'<a href="\' . get_category_link( $parent->term_id ) . \'" title="\' . esc_attr( sprintf( __( "View all posts in %s" ), $parent->name ) ) . \'">\' . $parent->name . \'</a>\' . $seperator . $categorylinks;
// get the next parent
$parent = get_term( $parent->parent, \'category\' );
}
// the actual category that is set, without the final Seperator
$categorylinks.= \'<a href="\' . get_category_link( $foundcategory->term_id ) . \'" title="\' . esc_attr( sprintf( __( "View all posts in %s" ), $foundcategory->name ) ) . \'">\' . $foundcategory->name . \'</a>\';
echo $categorylinks;
}
function howManyAncestors( $term ) {
$counter = 0;
$parent = get_term( $term->parent, \'category\' );
while ( $parent->term_id != $thiscategory->term_id && !is_wp_error( $parent ) && $parent->term_id != 0 ) {
$counter++;
$parent = get_term( $parent->parent, \'category\' );
}
return $counter;
}