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

WordPress分类页面分页仅显示2页问题求助(附代码)

修复WordPress自定义分类分页显示不全的问题

问题根源

  1. get_posts不支持分页计算:get_posts返回的是文章数组,而非包含分页元数据的WP_Query对象,无法获取总页数参数,导致paginate_links无法正确计算全部页码。
  2. 自定义分类参数使用错误:不能直接用'categorie' => ...作为查询参数,自定义分类筛选必须通过tax_query实现。
  3. 循环判断逻辑冗余:代码里的if (have_posts())是检查WordPress默认主查询,和你自定义的文章列表无关,逻辑无效。

修复步骤

1. 用WP_Query替代get_posts

WP_Query会返回完整的查询对象,包含max_num_pages(总页数)等分页关键信息,是实现自定义分页的标准方式。

2. 用tax_query筛选自定义分类

针对自定义分类categorie,通过tax_query指定分类的slug,确保筛选逻辑生效。

3. 给paginate_links传入总页数参数

从WP_Query对象中提取max_num_pages,让分页链接可以正确计算出所有页码。

4. 修正循环判断与遍历逻辑

直接基于自定义查询对象判断文章是否存在,并用while循环遍历,符合WordPress规范且无需手动处理全局文章变量。

完整修正代码

<?php
// 处理首页页码:默认paged为0,转为1避免查询异常
$currentPage = max(1, get_query_var('paged'));

$args_overview = array(
    'post_type' => 'nieuws',
    'post_status' => 'publish',
    'posts_per_page' => 4,
    'paged' => $currentPage,
    // 正确筛选自定义分类
    'tax_query' => array(
        array(
            'taxonomy' => 'categorie', // 自定义分类的注册名称
            'field'    => 'slug',
            'terms'    => get_queried_object()->slug,
        ),
    ),
);
// 创建自定义查询对象
$posts_overview = new WP_Query($args_overview);
?>
<div class="wpb-category__filter-posts">
    <?php
    // 判断自定义查询是否有文章
    if ($posts_overview->have_posts()) :
        // 启动自定义循环
        while ($posts_overview->have_posts()) : $posts_overview->the_post();
        ?>
            <div href="#" class="wpb-category__post-item">
                <div class="wpb-category__post-item-top">
                    <a href="<?= get_permalink(); ?>">
                        <?= wpb_image(get_field('algemeen')['afbeelding'], 'auto', 'auto') ?>
                    </a>
                </div>
                <div class="wpb-category__post-item-bottom">
                    <strong><?= get_the_title(); ?></strong>
                    <a href="<?= get_permalink(); ?>">
                        <p>Lees meer</p>
                    </a>
                </div>
            </div>
        <?php
        endwhile;
        wp_reset_postdata();
        
        // 生成完整分页链接,传入总页数
        echo "<div class='page-nav-container'>" . paginate_links(array(
            'total' => $posts_overview->max_num_pages,
            'prev_text' => __('&lt;'),
            'next_text' => __('&gt;')
        )) . "</div>";
    endif;
    ?>
</div>

额外说明

  • max(1, get_query_var('paged'))确保首页页码为1,避免paged=0导致的查询异常。
  • 使用while循环替代foreach,自动维护全局文章变量,get_permalink()、get_the_title()等函数无需手动传入$post对象。
  • wp_reset_postdata()必须在自定义循环结束后调用,恢复全局文章数据,避免影响后续查询逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 19:01:25