WordPress主题文章页面,相关文章调用的循环标签,调用相关文章数量6个

风中赏雪 Wordpress Wordpress 2025-09-27 122 0
<?php
// 获取当前文章的ID
$current_post_id = get_the_ID();

// 获取当前文章的分类ID(以第一个分类为例)
$categories = get_the_category($current_post_id);
if ($categories) {
    $category_ids = array();
    foreach ($categories as $category) {
        $category_ids[] = $category->term_id;
    }

    // 构建相关文章查询参数
    $args = array(
        'category__in'        => $category_ids, // 相同分类
        'post__not_in'        => array($current_post_id), // 排除当前文章
        'posts_per_page'      => 6, // 显示6篇
        'ignore_sticky_posts' => 1, // 忽略置顶文章
        'orderby'             => 'rand', // 随机排序(可选:date/comment_count)
    );

    $related_query = new WP_Query($args);

    if ($related_query->have_posts()) :
        echo '<h3>相关文章</h3>';
        echo '<ul class="related-posts">';
        while ($related_query->have_posts()) : $related_query->the_post();
            ?>
            <li>
                <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
                    <?php 
                    // 显示缩略图(需主题支持)
                    if (has_post_thumbnail()) {
                        the_post_thumbnail('thumbnail');
                    }
                    the_title(); // 显示标题
                    ?>
                </a>
            </li>
            <?php
        endwhile;
        echo '</ul>';
        // 重置主查询数据
        wp_reset_postdata();
    else :
        echo '<p>暂无相关文章</p>';
    endif;
}
?>