作为对更新代码的回复,您应该知道$post_terms = wp_get_object_terms()
只会返回直接附加到帖子的类别,所以我只使用wp_list_categories()
获取并显示给定父类别(或已知父类别)的子类别。
这里的代码对我来说很有用,它显示了多达三个级别的子类别,包括那些没有帖子的子类别。此代码将替换从$page_id = get_queried_object_id();
到$terms = wp_list_categories();
如问题所述,我正在使用get_ancestors()
而不是(你的)smart_category_top_parent_id()
:
$page_id = get_queried_object_id();
$category = get_the_category( $page_id );
$catid = ( ! empty( $category ) ) ? $category[0]->cat_ID : 0;
if ( $catid ) {
// Get all parent IDs.
$parents = get_ancestors( $catid, \'category\', \'taxonomy\' );
$top_level_cat = ( count( $parents ) > 1 ) ?
$parents[ count( $parents ) - 2 ] : // use the second parent category ID, or
array_pop( $parents ); // otherwise, we\'ll use the first one
$terms = wp_list_categories( array(
\'title_li\' => \'\',
\'echo\' => false,
\'taxonomy\' => \'category\',
\'show_count\' => 1,
\'child_of\' => $top_level_cat,
\'style\' => \'list\',
\'hide_empty\' => 0, // include empty categories
\'depth\' => 3, // and up to 3 levels depth
) );
}