Efficient REST API requests: _fields, _embed and pagination headers
A post in the default REST API response has about thirty fields: rendered and raw content, GUID, links, meta, template and more. A front end that shows a list of titles with images and authors needs a small part of it, but without care it downloads all of it and then makes extra requests for every image and author. Three built-in parameters fix that.
Problem: A JavaScript post list downloads full post objects and then requests the featured image and the author of every post separately.
Solution: Limit the response with _fields, include linked objects with _embed (since WordPress 5.4 also only selected ones, like _embed=author,wp:featuredmedia), and read the totals from the X-WP-Total and X-WP-TotalPages headers.
The request
async function fetchPosts( page, perPage ) {
const params = new URLSearchParams( {
_fields: 'id,title,excerpt,date,link,_links,_embedded',
_embed: 'author,wp:featuredmedia',
per_page: perPage,
page: page
} );
const response = await fetch( '/wp-json/wp/v2/posts?' + params.toString() );
if ( ! response.ok ) {
throw new Error( 'REST API error ' + response.status );
}
const posts = await response.json();
return {
totalPages: parseInt( response.headers.get( 'X-WP-TotalPages' ), 10 ),
total: parseInt( response.headers.get( 'X-WP-Total' ), 10 ),
posts: posts.map( function ( post ) {
const embedded = post._embedded || {};
const author = embedded.author && embedded.author[ 0 ];
const media = embedded[ 'wp:featuredmedia' ] && embedded[ 'wp:featuredmedia' ][ 0 ];
return {
id: post.id,
title: post.title.rendered,
excerpt: post.excerpt.rendered,
link: post.link,
author: author ? author.name : '',
image: media && media.media_details && media.media_details.sizes && media.media_details.sizes.medium
? media.media_details.sizes.medium.source_url
: ( media ? media.source_url : null )
};
} )
};
}
_embed follows the links in _links, so when _fields is used, _links and _embedded must be in the list; otherwise the embedded objects are dropped. Combining the two parameters works since WordPress 5.4.
Pagination
The body contains only the posts; the totals come in headers. A “load more” button needs only X-WP-TotalPages:
let page = 1;
document.querySelector( '.load-more' ).addEventListener( 'click', async function ( event ) {
const button = event.currentTarget;
const result = await fetchPosts( ++page, 10 );
renderPosts( result.posts ); // your own function that adds the cards
button.hidden = page >= result.totalPages;
} );
per_page is limited to 100. A page beyond the last one returns a 400 error (rest_post_invalid_page_number), not an empty list, so stop at totalPages.
Rendered content in lists
title.rendered and excerpt.rendered contain HTML (entities, <p> tags). Insert them as HTML only when you trust the site, or strip the tags for plain text. For headless use in general, see the REST API as a headless CMS backend.
NOTE: Responses for guests can be cached by a CDN like any other URL. Keep the parameters in a fixed order and use the same _fields list everywhere, so all visitors hit the same cached URL instead of many slightly different ones.