如何在WordPress循环中显示文章选中的子分类
问题描述
我有隶属于「news」分类的若干子分类:
- News
- news-topic-1
- news-topic-2
- news-topic-3
我设置了一个仅展示news分类下文章的循环,但希望只显示文章发布时选中的子分类,例如:
- Post 1
- news-topic-1
- Post 2
- news-topic-2
当前循环要么显示所有news相关子分类,要么仅显示首个子分类,无法精准展示文章选中的子分类。我的循环代码如下:
$args = array( 'posts_per_page' => 8, 'category_name' => 'news', ); $query = new WP_Query($args); if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post();?> <p class="cat_list_pots__content__subcat"> <?php $subcategories = get_categories(get_the_ID()); var_dump($subcategories); $subCatArry = []; foreach ($subcategories as $subcategory) { $subcategorySLUG = strtolower($subcategory->slug); array_push($subCatArry, $subcategory->name); } echo $subCatArry[count($subCatArry) - 1]; ?> </p> <?php endwhile; ?> <?php else: echo "<p>" . $message . "</p>"; endif; ?>
解决方案
核心问题是你误用了get_categories()函数,它是用来查询全站分类列表的,而非获取当前文章关联的分类。正确的做法是用get_the_category(),再过滤出news的子分类:
$args = array( 'posts_per_page' => 8, 'category_name' => 'news', ); $query = new WP_Query($args); if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); // 获取当前文章的所有关联分类 $post_categories = get_the_category(); $target_subcats = []; if ( !empty($post_categories) ) { foreach ( $post_categories as $cat ) { // 筛选news分类的子分类(news的slug需匹配实际设置) $parent_cat = get_category($cat->parent); if ( $cat->parent !== 0 && $parent_cat->slug === 'news' ) { $target_subcats[] = $cat->name; } } } // 输出选中的子分类,多分类用逗号分隔,按需调整 if ( !empty($target_subcats) ) { echo '<p class="cat_list_pots__content__subcat">' . implode(', ', $target_subcats) . '</p>'; } endwhile; wp_reset_postdata(); // 重置查询,避免后续数据冲突 else: echo "<p>" . $message . "</p>"; endif;
关键修改说明
- 替换分类获取函数:
get_the_category()专门用于获取当前文章的关联分类,而非全站分类。 - 子分类过滤逻辑:通过判断分类的父级是否为news分类,排除父分类本身,只保留目标子分类。
- 兼容多分类场景:用
implode()拼接多个子分类,若确定单分类可直接取数组第一个元素$target_subcats[0]。 - 重置查询:添加
wp_reset_postdata(),避免自定义查询干扰后续全局查询。
内容的提问来源于stack exchange,提问作者Felipe
相关产品推荐
相关产品推荐

