假设只有两个级别的类别,可以先检索父类别,然后列出子类别。此外,呼叫get_children
和wp_list_categories
使用的资源比需要的多,仅使用wp_list_categories
就足够了。我已经在下面的代码片段中解释了我的答案,它的行为应该完全符合您的需要!
$category_id = get_query_var( \'cat\' ); // Get current catgory ID
$category = get_term( $category_id, \'category\' ); // Fetch category term object
// Now, we check if the category has a parent
// If it has, we use that ID
// If it doesn\'t have a parent, it is a parent category itself and we use its own ID
$parent = $category->parent ? $category->parent : $category_id;
$args = array(
\'show_count\' => false,
\'hide_empty\' => false,
\'title_li\' => \'\',
\'show_option_none\' => \'\',
\'echo\' => false
);
// Show the children of parent category
if ( $category->parent ) {
$args[\'child_of\'] = $category->parent;
$args[\'exclude\'] = $category_id; // Don\'t display the current category in this list
}
else {
$args[\'child_of\'] = $category_id;
}
// Get the category list
$categories_list = wp_list_categories( $args );
if ( $categories_list ) {
?>
<div class="category-wrapper">
<ul class="child-categories">
<?php echo $categories_list; ?>
</ul>
</div>
<?php
}