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

设置置顶文章后get_the_posts_pagination()分页异常求助

我碰到过好多次这个问题,其实根源就是WordPress对置顶文章的默认处理逻辑和分页机制有点“不对付”——置顶文章会被强制放在首页最前面,但分页的时候系统不会自动把已经显示过的置顶从后续页面中排除,要么导致重复显示,要么让分页的帖子计数乱掉。结合你的代码,我给你分两种情况来解决:

情况1:你用的是WordPress默认的主查询(比如首页、分类归档页的原生查询)

首先,先把你代码里多余的wp_reset_postdata()删掉——这个函数是给自定义查询用的,主查询循环根本不需要它,留着反而可能干扰正常的分页逻辑。

然后,把下面这段代码加到你主题的functions.php文件里,它会帮你在分页页面自动排除已经显示过的置顶文章:

function fix_sticky_posts_pagination( $query ) {
    // 只处理前台的主查询,并且是分页页面
    if ( ! is_admin() && $query->is_main_query() && $query->is_paged() ) {
        $sticky_posts = get_option( 'sticky_posts' );
        if ( ! empty( $sticky_posts ) ) {
            $query->set( 'post__not_in', $sticky_posts );
        }
    }
}
add_action( 'pre_get_posts', 'fix_sticky_posts_pagination' );

这段代码的逻辑很简单:当用户访问第二页及以后的页面时,让主查询自动排除所有置顶文章,因为这些置顶已经在第一页展示过了。

情况2:你用的是自定义WP_Query(自己写的查询语句)

如果你的文章列表是用自定义查询生成的,那get_the_posts_pagination()就不适用了——这个函数是专门为主查询设计的,它会读取全局的$wp_query变量,用在自定义查询上肯定会出问题。你需要改用paginate_links(),同时在查询时就处理置顶文章的排除逻辑:

// 获取当前页码,默认是第一页
$paged = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;

// 构建查询参数
$args = array(
    'posts_per_page' => 10, // 替换成你每页想显示的帖子数量
    'paged' => $paged
);

// 如果是分页页面(第二页及以后),排除所有置顶文章
if ( $paged > 1 ) {
    $args['post__not_in'] = get_option( 'sticky_posts' );
}

// 执行自定义查询
$custom_query = new WP_Query( $args );

// 循环输出文章
if ( $custom_query->have_posts() ) :
    while ( $custom_query->have_posts() ) : $custom_query->the_post();
        get_template_part( 'template-parts/content', get_post_format() );
    endwhile;

    // 生成分页导航
    echo '<div class="page-nation">';
    echo '<ul id="Pagination" class="pagination pagination-large">';
    echo paginate_links( array(
        'total'        => $custom_query->max_num_pages,
        'mid_size'     => 2,
        'prev_text'    => __( 'Previous', 'your-text-domain' ), // 替换成你的主题文本域
        'next_text'    => __( 'Next', 'your-text-domain' ),
        'type'         => 'list' // 生成列表格式,匹配你的HTML结构
    ) );
    echo '</ul>';
    echo '</div>';

    wp_reset_postdata(); // 自定义查询结束后必须重置,恢复全局文章数据
endif;

这样调整后,第一页会正常显示置顶+普通文章,后续分页只显示普通文章,分页逻辑就完全正常了。

内容的提问来源于stack exchange,提问作者Francis Alvin Tan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:03:05