如何通过WordPress Rest API获取总文章数以确定请求次数?
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 yourper_pagevalue (since you noted the max per page is 100, this will be the ceiling oftotal_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=100parameter in your initial request—X-WP-TotalPagesis calculated based on this value, so using the max limit minimizes your total requests. - If you add filters (like
?categories=5or?status=draft),X-WP-Totalwill 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

