如何显示父分类的子分类?如何在页面中获取当前分类的子分类?
如何获取并显示父分类的子分类
咱们一步步来解决你遇到的问题,先看你提供的代码,你是通过自定义字段category来获取父分类的,那我们就从这个场景入手,同时也会覆盖分类归档页获取当前分类子分类的情况。
第一步:获取父分类的有效ID
你的代码里用get_post_meta(get_the_id(), 'category', true)拿到了存储的分类值,这个值可能是分类ID或者slug,我们需要先把它转换成有效的分类ID:
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1; $category = get_post_meta( get_the_id(), 'category', true ); $parent_cat_id = 0; // 判断拿到的是分类ID还是slug if ($category) { if (is_numeric($category)) { $parent_cat_id = $category; } else { // 如果是slug,先转成分类对象 $parent_cat_obj = get_category_by_slug($category); if ($parent_cat_obj) { $parent_cat_id = $parent_cat_obj->term_id; } } }
第二步:获取该父分类的子分类
有了父分类ID后,就可以用get_categories()函数来筛选它的子分类了,这个函数支持很多参数来控制结果:
$child_categories = array(); if ($parent_cat_id > 0) { $child_categories = get_categories(array( 'parent' => $parent_cat_id, // 指定父分类ID 'hide_empty' => false, // false显示所有子分类,true只显示有文章的 'orderby' => 'name', // 按分类名称排序 'order' => 'ASC', // 升序排列 'taxonomy' => 'category' // 默认就是分类,可省略,自定义分类的话需要修改 )); }
第三步:把子分类显示在页面上
拿到子分类数组后,就可以循环输出了,记得用esc_url()和esc_html()做安全处理,避免XSS风险:
if (!empty($child_categories)) { echo '<div class="child-categories-wrap">'; echo '<h3>该分类的子分类</h3>'; echo '<ul class="child-cats-list">'; foreach ($child_categories as $cat) { $cat_link = get_category_link($cat->term_id); echo '<li>'; echo '<a href="' . esc_url($cat_link) . '">' . esc_html($cat->name) . '</a>'; // 可选:显示分类描述 if (!empty($cat->description)) { echo '<p class="cat-desc">' . esc_html($cat->description) . '</p>'; } echo '</li>'; } echo '</ul>'; echo '</div>'; } else { echo '<p>当前父分类没有子分类哦~</p>'; }
额外场景:分类归档页获取当前分类的子分类
如果是在分类归档页面(比如category.php),不需要自定义字段,直接获取当前页面的分类对象即可:
$current_category = get_queried_object(); if ($current_category instanceof WP_Term) { $child_categories = get_categories(array( 'parent' => $current_category->term_id, 'hide_empty' => false, 'orderby' => 'name', 'order' => 'ASC' )); // 然后用上面同样的循环代码显示子分类 }
把这些代码整合起来,就能完美实现你要的功能啦~
内容的提问来源于stack exchange,提问作者Anil Kumar
相关产品推荐
相关产品推荐

