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

WordPress分页仅首页生效,自定义页面无响应问题求助

解决WordPress自定义页面分页无效问题

核心问题分析

  1. 分页变量差异:WordPress里博客首页、归档页用paged作为分页参数,而静态自定义页面模板使用page参数,直接调用get_query_var('paged')在自定义页面拿不到正确的分页值。
  2. 分页函数依赖主查询:next_posts_link()和previous_posts_link()默认使用主查询的max_num_pages,自定义查询必须手动传入该值,否则函数会误判没有更多页面,不输出分页链接。

修改后的完整代码

<?php
// 同时获取paged和page参数,兼容首页与自定义页面
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : ( get_query_var('page') ? get_query_var('page') : 1 );

$args = array(
    'post_type' => 'post',
    'posts_per_page' => get_option( 'posts_per_page' ),
    'paged' => $paged,
    'post_status' => 'publish',
    'category_name' => 'home',
);
$arr_posts = new WP_Query( $args );

if ( $arr_posts->have_posts() ) :
    while ( $arr_posts->have_posts() ) : $arr_posts->the_post(); ?>

        <div class="swiper-slide frontpage-slide">
            <?php if ( has_post_thumbnail() ) { the_post_thumbnail( 'large', array('class' => 'first-image') ); } ?>
            <h1 class="post_title"><?php the_title(); ?></h1>
            <?php the_content(); ?>
        </div>

    <?php endwhile; ?>
<?php endif; ?>

<div class="swiper-slide pagination-slide">
    <nav class='pagination'>
        <div class="newer-link">
            <?php 
            // 传入自定义查询的max_num_pages参数
            previous_posts_link( 
                '<span><svg id="Ebene_2" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 211.41 211.41"><defs><style>.cls-1{fill:#fff;}</style></defs><g id="Ebene_1-2"><path class="cls-1" d="M0,0H211.41V11.75H20.03L155.36,147.08l-8.28,8.28L11.75,20.03V211.41H0V0Z"/></g></svg></span><span class="pagination-text-newer">newer&nbsp;posts</span>',
                $arr_posts->max_num_pages
            ); 
            ?>
        </div>
        <div class="older-link">
            <?php 
            // 传入自定义查询的max_num_pages参数
            next_posts_link( 
                '<span class="pagination-text-older">older&nbsp;posts</span><span><svg id="Ebene_2" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 211.41 211.41"><defs><style>.cls-1{fill:#fff;}</style></defs><g id="Ebene_1-2"><path class="cls-1" d="M0,199.67H191.39L56.06,64.33l8.28-8.28L199.67,191.39V0h11.75V211.41H0v-11.75Z"/></g></svg></span>',
                $arr_posts->max_num_pages
            ); 
            ?>
        </div>
    </nav>
</div>
<?php wp_reset_postdata(); // 重置查询,避免干扰全局post变量 ?>

关键修改点说明

  • 分页变量适配:优先获取paged适配首页、归档场景,若不存在则获取page适配自定义静态页面,最后默认设为1。
  • 分页函数传参:给两个分页函数添加第二个参数$arr_posts->max_num_pages,让函数基于你的自定义查询计算分页数量。
  • 重置查询:添加wp_reset_postdata(),确保自定义查询不会影响页面其他部分的全局post变量。

额外检查项

  • 确认category_name对应的分类下文章数量超过posts_per_page的设置值,否则分页不会显示。
  • 自定义页面需在后台选择对应的模板,且URL结构正确(分页会以/page/2的形式追加在URL后)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 20:45:34