You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WordPress循环展示最新文章时如何完整显示所有文章分类的技术咨询

嘿,我来帮你搞定这个显示所有文章分类的问题!

首先得说清楚你之前遇到的问题根源:

  • 你用get_the_category()没正常工作,大概率是因为这个函数返回的是分类对象数组,不能直接echo,必须遍历数组才能逐个输出分类;
  • 而wp_get_post_terms()只显示一个分类,是因为你直接取了数组的第一个元素[0]->name,没处理多分类的遍历逻辑。

下面给你两种可行的解决方案,直接就能用到你的代码里:

方法1:用get_the_category()(WordPress官方推荐的分类获取函数)

把这段代码放到你的.blog-post div里合适的位置(比如作者名称后面),就能遍历输出当前文章的所有分类:

<?php
// 获取当前文章的所有分类数组
$categories = get_the_category();
// 先检查是否有分类,避免空数组报错
if ( ! empty( $categories ) ) {
    echo '<div class="post-categories">';
    foreach ( $categories as $category ) {
        // 输出分类名称,这里加了esc_html防止XSS注入
        echo '<span class="category-item">' . esc_html( $category->name ) . '</span>';
        // 如果需要给分类加跳转链接,替换上面的echo为下面这段:
        // echo '<a href="' . esc_url( get_category_link( $category->term_id ) ) . '" class="category-item">' . esc_html( $category->name ) . '</a>';
    }
    echo '</div>';
}
?>

方法2:用wp_get_post_terms()(更灵活,支持自定义分类法)

如果你偏好这个函数,只需要修改成遍历整个分类数组的逻辑即可:

<?php
// 获取当前文章的所有分类,第三个参数确保返回完整的分类对象
$categories = wp_get_post_terms( get_the_ID(), 'category', array( 'fields' => 'all' ) );
// 检查是否获取成功(避免错误对象)
if ( ! empty( $categories ) && ! is_wp_error( $categories ) ) {
    echo '<div class="post-categories">';
    foreach ( $categories as $category ) {
        echo '<span class="category-item">' . esc_html( $category->name ) . '</span>';
        // 同样可选添加分类链接:
        // echo '<a href="' . esc_url( get_term_link( $category->term_id ) ) . '" class="category-item">' . esc_html( $category->name ) . '</a>';
    }
    echo '</div>';
}
?>

整合到你的完整代码里

给你调整好的最终代码,顺便把$the_query->ID改成了get_the_ID()——在while循环里调用the_post()后,get_the_ID()会自动获取当前循环文章的ID,比直接调用查询对象的ID更稳妥:

<?php $the_query = new WP_Query( 'posts_per_page=3' ); ?> 
<?php while ($the_query -> have_posts()) : $the_query -> the_post(); ?> 
<div class="blog-post"> 
    <?php echo get_the_post_thumbnail( get_the_ID(), array( 400, 0) ); ?> 
    <?php echo get_avatar( get_the_author_meta( 'ID') , 150); ?> 
    <?php echo get_the_author_meta('display_name', get_the_author_meta('ID')); ?> 
    <!-- 新增的分类输出代码 -->
    <?php
    $categories = get_the_category();
    if ( ! empty( $categories ) ) {
        echo '<div class="post-categories">';
        foreach ( $categories as $category ) {
            echo '<span class="category-item">' . esc_html( $category->name ) . '</span>';
        }
        echo '</div>';
    }
    ?>
</div> 
<?php endwhile; wp_reset_postdata(); ?>

内容的提问来源于stack exchange,提问作者FI_124

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 18:57:35