How to Add Meta Fields when Creating a Post with REST API

This tutorial is a small addition to my another tutorial about creating posts with REST API in WordPress, because there I didn’t mention how to work with metadata and what moments you have to keep in mind.

As a result of this tutorial we will just create a simple draft post with a couple custom fields in it.

Registering Meta Fields in REST API

First of all let me remind what we will have two websites:

And our goal now is to register every custom field we are going to create with API using register_meta() function. This code is for Site 1.

add_action( 'rest_api_init', function(){

	register_meta( 
		'post', 
		'event_location', 
		array(
			'type' => 'string',
			'single' => true,
			'show_in_rest' => true
		)
	);
	
	register_meta( 
		'post', 
		'event_date', 
		array(
			'type' => 'string',
			'single' => true,
			'show_in_rest' => true
		)
	);
	
} );

A moment to remember when working with custom post types

It doesn’t relate to regular posts or pages, but when you’re registering a custom post type you should pay a special attention to supports argument. It should contain custom-fields value in it. Example:

register_post_type(
	'rudr_post_type',
	array(
		
		/* some parameters will be here */
		
		'supports' => array( 'title', 'editor', 'custom-fields' ),
	)
);

Create a Post with Custom Fields

Below is the code, in case something is not clear in it, I suggest you to read this tutorial first.

wp_remote_post(
		'https://WEBSITE-DOMAIN/wp-json/wp/v2/posts',
		array(
			'headers' => array(
				'Authorization' => 'Basic ' . base64_encode( "$login:$password" )
			),
			'body' => array(
				'title'   => 'My test',
				'status'  => 'draft',
				'meta' => array(
					'event_location' => 'Athens',
					'event_date' => 'Tomorrow'
				)
			)
		)
);

But finally we have this:

Create a post with REST API with custom fields
Misha Rudrastyh

Misha Rudrastyh

Hey guys and welcome to my website. For more than 10 years I've been doing my best to share with you some superb WordPress guides and tips for free.

Need some developer help? Contact me

Follow me on Twitter