We can use the existing meta
property (see docs) to add multiple meta fields (in a JSON format) when we create a post via POST method:
POST: example.com/wp-json/wp/v2/posts/
Body payload:
{
"title": "My title",
"content": "My content",
"meta": {"myfield1":"myvalue1", "myfield2":"myvalue2"}
}
or when we want to update a post with ID 123:
POST: example.com/wp-json/wp/v2/posts/123
Body payload:
{
"title": "My title 2",
"content": "My content 2",
"meta": {"myfield1":"myvalue11", "myfield2":"myvalue22"}
}
Note that we will have to register the meta fields with corresponding schema properties (see docs and docs), for example registering meta field myfield1
as a string with:
add_action( 'rest_api_init', function() {
register_post_meta(
'post', // post type
'myfield1', // meta key
array(
'single' => true,
'type' => 'string',
'show_in_rest' => array(
'schema' => array(
'type' => 'string',
'default' => '',
),
),
)
);
} );
We can see how the meta
scheme property is checked in the rest posts controller:
if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) {
$meta_update = $this->meta->update_value( $request['meta'], $post_id );
if ( is_wp_error( $meta_update ) ) {
return $meta_update;
}
}
https://developer.wordpress.org/reference/classes/wp_rest_posts_controller/create_item/