Building a custom settings page in WordPress using React, I faced the situation where I wanted to update meta fields of multiple posts at once. I want to share the approach I used with the WordPress REST API.
The WordPress REST API has a framework for making a series of REST API calls at once. It is handy to update meta fields of multiple posts using a single REST request. The framework name is REST API Batch Framework. Next are the steps I took to use it.
Registration of the meta fields in the REST API
First I registered the custom meta field in the REST API using the register_post_meta function.
add_action( 'init', function() {
register_post_meta(
'post',
'my_custom_field_name',
[
'single' => true,
'type' => 'string',
'show_in_rest' => true,
]
);
} );
- The first argument I used here is
'post'
, which means that the custom field is applied for items saved in the posts table (posts, pages and custom post types). Here you can use other entities like'comment'
,'term'
or'user'
. If the meta field is used in a custom post type, then the custom post type should support custom fields. During the custom post type registration, you can use thesupports
field to addcustom-fields
. - The second argument is
'my_custom_field_name'
which is the key name used for the meta field. - The last argument describes the meta field. In this example, the meta field has one value per post only, its type is string and its value is accessible via the REST API. Indeed, the value of the
'show_in_rest'
key can be an array with the key'schema'
to describe its data structure in the REST API.
Using the Batch Framework to update meta fields of multiple posts in WordPress
The React component uses the Batch Framework and it is in charge of doing the request to update the posts. It has a function to update the meta fields of multiple posts in WordPress using a single request. The request looks like this:
const requests = [
{
path: '/wp/v2/posts/10',
method: 'POST',
body: {
meta: {
my_custom_field_name: 'hello world',
},
},
},
{
path: '/wp/v2/posts/11',
method: 'POST',
body: {
meta: {
my_custom_field_name: 'lorem ipsum...',
},
},
},
{
path: '/wp/v2/posts/12',
method: 'POST',
body: {
meta: {
my_custom_field_name: '123abc',
},
},
}
];
apiFetch( {
path: 'batch/v1',
method: 'POST',
data: { requests },
} )
.then( response => handleBatchResponse( response, requests ) )
.catch( err => console.log( err ) );
The apiFetch
call use the next config object:
- The
path
and themethod
properties of the Batch Framework endpoint,batch/v1
andPOST
respectively. - The
data
property is an object with the propertyrequests
which contains an array with the configuration of each one of the requests we want to execute. Each configuration is an object with the required propertypath
and optionally the propertiesmethod
,headers
andbody
. In this case, these are the configuration to make the requests to the WordPress endpointPOST /wp/v2/posts/<id>
to update the posts.
Handling the response
Finally here is how to handle the response of the request to update meta fields of multiple posts in WordPress. In the React component, I defined the next function:
const handleBatchResponse = ( batchResponse, requests ) => {
batchResponse.responses.forEach( ( requestResponse, idx ) => {
// Get the data of the request related to the current response.
const requestData = requests[ idx ];
// Check if the response was not successful.
if ( 200 !== requestResponse.status ) {
// Show error message here.
}
} );
} );
The custom function handleBatchResponse
expects 2 parameters, the response of the batch request and the array of requests sent in the batch request. This function is called when the response of the request is received and parsed by the apiFetch
call. The response of the batch requests is an object with the property responses
which is an array of enveloped responses objects for each one of the requests sent in the batch request. Each enveloped response has the properties status
, headers
and body
. The order of the items in the responses
array corresponds to the order of the items in the requests
array sent in the batch request, so the first object in batchResponses.responses
is the response of the first object in the requests
array.
Conclusion
It is possible to update meta fields of multiple posts in WordPress using a single REST requests. The REST API Batch Framework allows to run multiple requests at once in WordPress. However, take into account that it accepts up to 25 requests in a single batch. Additionally, the framework doesn’t support GET requests. Using parallel requests or linking and embedding are the recommendation in this case.