如何在WordPress自定义文章类型Spotlights的循环中显示对应分类法?
解决Spotlight自定义文章类型循环中显示所属分类的问题
嗨,我来帮你搞定这个问题!你的核心问题是获取分类的方式不对——原代码里用get_terms($taxonomy)拿到的是整个分类法下的所有分类,而不是当前文章实际关联的分类,所以自然没法对应到每篇文章。
修改后的完整循环代码
<?php $args = array( 'post_type' => 'spotlight', 'orderby' => 'date', 'order' => 'DESC', 'posts_per_page' => 2 ); $query = new WP_Query( $args ); $taxonomy = 'category-spotlight'; if ($query->have_posts()): ?> <?php while ($query->have_posts()): $query->the_post(); ?> <h3 class="small"><?php the_title(); ?></h3> <?php // 获取当前文章关联的分类术语 $post_terms = get_the_terms(get_the_ID(), $taxonomy); if (!empty($post_terms) && !is_wp_error($post_terms)) { // 如果每个文章只关联一个分类,直接取第一个 $term = reset($post_terms); echo '<div class="category">' . esc_html($term->name) . '</div>'; // 若需显示多个分类(逗号分隔),可替换上面的echo为这段: // $term_names = wp_list_pluck($post_terms, 'name'); // echo '<div class="category">' . esc_html(implode(', ', $term_names)) . '</div>'; } ?> <?php endwhile; ?> <?php wp_reset_postdata(); // 重置查询,恢复全局$post变量,避免影响后续内容 ?> <?php endif; ?>
关键修改点说明
- 替换分类获取函数:用
get_the_terms(get_the_ID(), $taxonomy)替代get_terms($taxonomy),这个函数专门用来获取当前文章关联的指定分类法术语,完美匹配你的需求。 - 增加安全检查:通过
!empty($post_terms) && !is_wp_error($post_terms)确保获取到有效数据,避免因无分类或查询错误导致的页面报错。 - 灵活处理单/多分类:默认只显示第一个关联分类,如果你的文章可能绑定多个分类,只需注释掉单分类代码,启用多分类显示的片段即可。
- 添加查询重置:循环结束后调用
wp_reset_postdata()是WordPress开发的最佳实践,能恢复全局$post变量,防止后续代码出现异常。
另外提一句:你注册分类法时把public设为false但开启了show_in_rest,如果不需要在REST API中暴露这个分类法,可以根据实际需求调整,但这不会影响前端的分类显示效果。
内容的提问来源于stack exchange,提问作者Light_Warrior
相关产品推荐
相关产品推荐

