
在 WordPress 主循环或自定义查询中,可通过 $query->post_count 获取当前分页页码所显示的帖子数量,结合 $query->found_posts 即可实现如“显示 5 条中的第 1–5 条”这类清晰的分页提示。
在 wordpress 主循环或自定义查询中,可通过 `$query->post_count` 获取当前分页页码所显示的帖子数量,结合 `$query->found_posts` 即可实现如“显示 5 条中的第 1–5 条”这类清晰的分页提示。
在 WordPress 开发中,常需向用户展示分页上下文信息,例如:
“显示第 1–8 篇(共 47 篇)” 或 “Showing 5 of 50 posts”。
其中,“50”对应总文章数(即 $query->found_posts),而“5”则代表当前页实际显示的文章条数——这正是 $query->post_count 的作用。
✅ 正确用法示例
// 在主循环中(如 index.php、archive.php)
global $wp_query;
$total = $wp_query->found_posts; // 所有符合条件的文章总数(含分页)
$current_page_count = $wp_query->post_count; // 当前页实际显示的文章数(如每页 10 条,则第 1–4 页为 10,末页可能为 7)
// 计算当前页起始序号(从 1 开始计数)
$paged = get_query_var('paged') ?: 1;
$posts_per_page = get_option('posts_per_page');
$offset = ($paged - 1) * $posts_per_page;
$start_num = $offset + 1;
$end_num = min($offset + $current_page_count, $total);
// 输出:Showing 1–8 of 47 posts
echo sprintf(
'Showing %d–%d of %d posts',
$start_num,
$end_num,
$total
);
? 注意:$query->post_count 是动态值,它反映 WP_Query 实际执行后返回的 $posts 数组长度,因此:
- 在 pre_get_posts 钩子中尚不可用(此时查询未执行);
- 在 loop_start、the_post 或循环结束后访问才可靠;
- 对于主循环,推荐在 while (have_posts()) : the_post(); 之后或循环外使用 $wp_query;
- 若使用自定义 WP_Query,请确保已调用 $custom_query->get_posts() 或已进入其循环。
⚠️ 常见误区提醒
- ❌ 不要用 count($wp_query->posts) 替代 $wp_query->post_count:虽然多数情况下结果一致,但 post_count 是经过内部校验的权威值,且更语义明确;
- ❌ 不要混淆 post_count 与 found_posts:前者是“本页数量”,后者是“全量匹配数”;
- ✅ 若需兼容自定义分页逻辑(如 AJAX 加载),建议将 $start_num 和 $end_num 的计算逻辑封装为辅助函数,便于复用。
通过合理组合 $wp_query->post_count 与 $wp_query->found_posts,你不仅能精准呈现分页统计信息,还能提升用户体验与界面专业度。











