WordPress主题分类页面,调用本分类10篇文章的循环标签,循环标签的文章列表需要获取该文章的分类名以及分类链接

风中赏雪 Wordpress Wordpress 2025-09-27 107 0

<?php
// 确保在分类模板文件(如category.php)中使用
if (have_posts()) :
    while (have_posts()) : the_post();
        // 获取当前文章的所有分类(返回数组)
        $categories = get_the_category();
        if (!empty($categories)) :
            // 获取第一个分类(可根据需要修改逻辑)
            $first_category = $categories&#91;0&#93;;
            ?>
            <article>
                <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
                
                <!-- 显示分类名称和链接 -->
                <div class="post-category">
                    分类: 
                    <a href="<?php echo esc_url(get_category_link($first_category->term_id)); ?>">
                        <?php echo esc_html($first_category->name); ?>
                    </a>
                </div>
            </article>
        <?php
        endif;
    endwhile;
    
    // 重置主循环
    wp_reset_postdata();
else :
    echo '没有找到文章';
endif;
?>

关键函数说明:

1.get_queried_object()
获取当前分类页面的分类对象(包含term_id、name等信息)

2.get_the_category()
获取当前文章的所有分类信息数组

3.get_category_link( $term_id )
通过分类ID获取分类归档页链接

4.wp_reset_postdata()
重置循环数据(使用自定义查询时必须调用)