如何在WordPress循环中显示文章所属分类
修复主循环中显示文章分类的问题
你的代码问题出在 wp_get_post_categories() 的返回值上 —— 这个函数默认只返回分类ID的数组,而不是完整的分类对象。所以在 foreach 循环里,$cat 其实是一个数字ID,而不是包含 cat_ID 和 name 属性的对象,自然无法正确输出链接和分类名称。
这里有两种简单的修复方案,任选其一即可:
方案1:修改 wp_get_post_categories 的参数,返回分类对象
只需要给函数添加一个 fields 参数,让它返回完整的分类数据:
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <?php $id = get_the_ID(); // 添加 fields 参数,获取完整分类对象 $cats = wp_get_post_categories($id, array('fields' => 'all')); ?> <?php foreach ( $cats as $cat ): ?> <!-- 这里用 $cat->term_id 代替 $cat->cat_ID,或者直接传入 $cat 对象给 get_category_link --> <a href="<?php echo get_category_link($cat->term_id); ?>"> <?php echo esc_html($cat->name); ?> <!-- 加上 esc_html 确保安全输出 --> </a> <?php endforeach; ?> <h5 class="card-title"><?php the_title(); ?></h5> <p class="card-text"><?php the_excerpt(); ?></p> <?php endwhile; else: ?> <p>Sorry, this page does not exist</p> <?php endif; ?>
方案2:使用更简洁的 get_the_category() 函数
在主循环中,get_the_category() 会自动获取当前文章的分类对象数组,不需要手动传文章ID,代码更简洁:
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <?php $cats = get_the_category(); ?> <?php foreach ( $cats as $cat ): ?> <a href="<?php echo get_category_link($cat); ?>"> <?php echo esc_html($cat->name); ?> </a> <?php endforeach; ?> <h5 class="card-title"><?php the_title(); ?></h5> <p class="card-text"><?php the_excerpt(); ?></p> <?php endwhile; else: ?> <p>Sorry, this page does not exist</p> <?php endif; ?>
额外提醒
- 不要忘记用
esc_html()包裹分类名称,这是WordPress的安全最佳实践,防止XSS注入。 - 如果文章没有分类,
get_the_category()会返回空数组,循环不会执行,避免输出错误内容。
内容的提问来源于stack exchange,提问作者JMKelley
相关产品推荐
相关产品推荐

