WordPress REST API Pagination: Fetch Every Page Without Guessing
A request to /wp-json/wp/v2/posts returning ten posts does not mean a site has only ten. WordPress REST API collections are paginated. A client that assumes its first response is complete can silently omit older records from a migration, search index or report.
Editorial illustration: each response represents one page in a changing collection.
Summary
- Set a practical
per_pageand incrementpage; WordPress caps the page size at 100. - Read
X-WP-TotalandX-WP-TotalPagesas response-time metadata, and handle HTTP errors explicitly. - For large or changing collections, checkpoint progress and decide how to handle content added during the export.
Make pagination visible
curl -i 'https://example.com/wp-json/wp/v2/posts?per_page=50&page=1'
The body is a JSON array. Response headers include X-WP-Total and X-WP-TotalPages for the collection at request time. per_page defaults to a smaller page and cannot exceed 100. Filters such as search, after, categories or status change which records the total describes.
A small JavaScript client can continue until fewer than a full page is returned:
async function* allPosts(baseUrl) {
const perPage = 50;
for (let page = 1; ; page += 1) {
const url = new URL('/wp-json/wp/v2/posts', baseUrl);
url.searchParams.set('per_page', String(perPage));
url.searchParams.set('page', String(page));
const response = await fetch(url);
if (!response.ok) throw new Error(`HTTP ${response.status}, page ${page}`);
const posts = await response.json();
if (!Array.isArray(posts)) throw new Error('Expected a post array');
if (posts.length === 0) return;
yield* posts;
if (posts.length < perPage) return;
}
}
This is for public posts. Drafts, private posts and custom post types require suitable routes and permissions. Never put an application password in browser code or a public repository. See the official REST API pagination guide and posts endpoint reference.
Treat headers as a snapshot
X-WP-TotalPages helps plan work and display progress, but it describes the result when that request ran. If posts are added or deleted during a long export, the count can shift. Offset pagination can also encounter duplicates or omissions near a page boundary when the collection changes. Do not assume multiple HTTP requests form a frozen snapshot.
For a one-time migration, pause editorial changes or export from a controlled backup. For a recurring sync, store stable post IDs and modified timestamps, make writes idempotent, and checkpoint each successful page. If a page request fails, log its number and status. Retry transient network failures with a limit and backoff; don’t retry authentication or invalid-parameter errors forever.
Decide what “all posts” means
The default endpoint exposes published content to public visitors. It does not automatically mean every editorial record. Before fetching, decide whether the job includes drafts, private posts, custom post types or custom fields. Verify the endpoint schema and authentication behavior on the site. A successful response with fewer results can reflect permissions or filters rather than a broken loop.
For example, an importer that needs only published posts should not request privileged credentials. An editorial backup may need authentication and a server-side process. Keep credentials out of client-side JavaScript, logs and issue reports. For server-side integrations, see WordPress application passwords. Apply least privilege and rotate credentials if they are exposed.
Diagnose missing or repeated records
- Request page 1 with
per_page=1; inspect the headers and check that totals are plausible. - Request page 2 directly. Inspect status and body before interpreting an error as “no more records.”
- Remove filters one at a time. A date or category filter can legitimately narrow the response.
- Compare a few stable IDs across pages. Repeated IDs suggest a checkpoint or changing-content problem.
- Test the exact route and permissions. A custom post type must be exposed to REST and protected content requires authorized credentials. Our custom post type endpoint guide walks through route visibility.
A 400 or rest_post_invalid_page_number response is not equivalent to an empty JSON array. Validate status before parsing data, then handle the response according to its meaning. If your script stops because a server transiently failed, resume from the last confirmed page rather than silently treating partial data as complete.
Mistakes to avoid
- Requesting
per_page=500: use multiple bounded requests. - Counting JSON without checking status: error bodies are JSON too.
- Assuming totals never move: content can change between requests.
- Embedding credentials in frontend code: browser users can inspect them.
- Retrying all errors forever: authentication, permission and parameter errors need a different fix from timeouts.
My Take
The loop is the easy part. The useful question is what completeness means for the actual job. A public site changes while it is being read; a migration or audit may need a controlled snapshot and a record of exactly what succeeded.
Bottom Line
Request bounded pages, validate status and response shape, then advance until the collection ends. Use pagination headers as metadata rather than an unchanging promise. Add checkpoints and stable IDs for production syncs or migrations.