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

如何通过WordPress Rest API获取总文章数以确定请求次数?

How to Get Total Post Count from WP REST API to Determine Request Times

Great question! When working with the WP REST API's posts endpoint (/wp-json/wp/v2/posts), it actually gives you all the info you need right in the response headers—no extra endpoints or guesswork required. Let me break this down for you:

Key Response Headers to Look For

The API returns two critical headers that handle this exact use case:

  • X-WP-Total: The total number of posts that match your request (including any filters you apply, like category or status)
  • X-WP-TotalPages: The total number of request batches needed to fetch all posts, calculated based on your per_page value (since you noted the max per page is 100, this will be the ceiling of total_posts / 100)

How to Access These Headers

Example with cURL

Run a head request to get just the headers (this is faster than fetching the full first batch of posts):

curl -I http://demo.wp-api.org/wp-json/wp/v2/posts?per_page=100

You'll see output like this in the response headers:

X-WP-Total: 423
X-WP-TotalPages: 5

This tells you there are 423 total posts, so you need 5 requests (4 batches of 100, 1 batch of 23).

Example with JavaScript (Fetch API)

If you're working in code, you can grab these headers from the initial fetch response:

fetch('http://demo.wp-api.org/wp-json/wp/v2/posts?per_page=100')
  .then(response => {
    // Extract the total counts from headers
    const totalPosts = response.headers.get('X-WP-Total');
    const totalPages = response.headers.get('X-WP-TotalPages');
    
    console.log(`Total posts to fetch: ${totalPosts}`);
    console.log(`Number of requests needed: ${totalPages}`);

    // Loop through each page to fetch all posts
    for (let page = 1; page <= totalPages; page++) {
      fetch(`http://demo.wp-api.org/wp-json/wp/v2/posts?per_page=100&page=${page}`)
        .then(res => res.json())
        .then(posts => {
          // Process your posts here (e.g., save to a database, render content)
          console.log(`Fetched page ${page}: ${posts.length} posts`);
        });
    }
  })
  .catch(error => console.error('Error fetching posts:', error));

Important Notes

  • Always include the per_page=100 parameter in your initial request—X-WP-TotalPages is calculated based on this value, so using the max limit minimizes your total requests.
  • If you add filters (like ?categories=5 or ?status=draft), X-WP-Total will automatically update to reflect the count of posts matching those filters.
  • Some HTTP libraries or tools might hide response headers by default—double-check that your client allows access to these custom WP headers (most modern tools like fetch, Axios, or cURL do).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:50:11