如果您位于单个自定义帖子模板中,则可以使用
$terms = get_the_terms( get_the_ID(), \'btp_work_category\' );
然后,您需要确定父项并将其与其子项一起显示。
下面的代码假设帖子属于一个顶级类别(术语),分类树的级别不超过2级。
$terms = get_the_terms( get_the_ID(), \'btp_work_category\' );
if ( ! empty( $terms ) ) :
echo "<ul>\\n";
// Parent term detection and display
$term = array_pop( $terms );
$parent_term = ( $term->parent ? get_term( $term->parent, \'btp_work_category\' ) : $term );
echo "<li>\\n";
echo \'<a href="\' . get_term_link( $parent_term, \'btp_work_category\' ) . \'">\' . $parent_term->name . \'</a>\';
// Getting children
$child_terms = get_term_children( $parent_term->term_id, \'btp_work_category\' );
if ( ! empty( $child_terms ) ) :
echo "\\n<ul>\\n";
foreach ( $child_terms as $child_term_id ) :
$child_term = get_term_by( \'id\', $child_term_id, \'btp_work_category\' );
echo \'<li><a href="\' . get_term_link( $child_term, \'btp_work_category\' ) . \'">\' . $child_term->name . "</a></li>\\n";
endforeach;
echo "</ul>\\n";
endif; // ( ! empty( $child_terms ) )
echo "</li>\\n";
echo "</ul>\\n";
endif; // ( ! empty( $terms ) )