一旦您无法知道get_the_category
, 我建议遍历类别并填充两个数组,一个用于父级,一个用于子级。之后,如果父数组为空,则显示子数组,否则显示父数组:
$categories = get_the_category();
if ( ! empty($categories) ) {
$parents = array();
$children = array();
foreach( get_the_category() as $cat ) {
if ( $cat->parent == 0 ) {
$parents[] = $cat;
} else {
$children[] = $cat;
}
}
$toshow = ! empty($children) ? $children : $parents;
$sep = \'\';
if ( ! empty($toshow) ) { foreach( $toshow as $cat ) {
echo $sep;
echo \'<span class="\' . $cat->name .\'">\';
echo \'<a href="\' . get_category_link($cat->term_id) . \'">\' . $cat->name . \'</a></span>\';
$sep = \' / \';
} }
}