如何通过WordPress REST API获取网站文章总数?
获取WordPress标准REST API文章总数的方法
WordPress标准REST API的默认文章列表接口(wp-json/wp/v2/posts/)不会直接返回总数,但有两种实用方法可以拿到:
1. 从响应头获取总数(无需改代码)
发送请求时带上per_page=1和_fields=id参数,接口返回的响应头里会有X-WP-Total字段,这个值就是已发布文章的总数量。
示例请求:
GET https://www.punjabidharti.com/wp-json/wp/v2/posts/?per_page=1&_fields=id
之后在响应头里读取X-WP-Total,就能得到你要的总数(比如之前的34470)。
2. 自定义REST端点返回总数(需要改代码)
如果想直接在响应体里拿到总数,可以在主题的functions.php文件中添加以下代码:
add_action('rest_api_init', function () { register_rest_route('custom/v1', '/post-total', [ 'methods' => 'GET', 'callback' => 'get_total_posts_count', 'permission_callback' => '__return_true' ]); }); function get_total_posts_count() { return ['count_total' => wp_count_posts()->publish]; }
添加完成后,访问https://www.punjabidharti.com/wp-json/custom/v1/post-total,就能直接拿到包含count_total的JSON结果。
补充说明
- 第一种方法零代码改动,适合快速获取;
- 第二种方法需要服务器权限修改主题文件,适合需要固定接口返回总数的场景;
- 确保你的WordPress版本在4.7及以上,这个版本才默认支持标准REST API。
内容的提问来源于stack exchange,提问作者noorapps
相关产品推荐
相关产品推荐

