Include Meta Data When Updating Users via REST API
In my another tutorial about syncing users using WordPress REST API I received a question in comments, where I was asked about metadata. After googling for quite a bit I found out that there is no clear explanation out there about using user’s meta in REST API requests.
So, here we go, let’s figure it out right now.
Before we dive into the actual code, I would like to bring your attention to a moment that it is super-similar to how we worked with metadata in REST API requests for posts.
First, we need a request, let’s say that we are about to update an existing user on our website.
wp_remote_post(
"{$url}/wp-json/wp/v2/users/{$user_id}",
array(
'headers' => array(
'Authorization' => 'Basic ' . base64_encode( "{$login}:{$password}" )
),
'body' => array(
'first_name' => 'Misha',
'meta' => array(
'city' => 'Dubai',
'age' => 29,
),
)
)
);
As you can see I included two meta keys above, but don’t get excited too soon, if you run this REST API request, nothing will happen except a user first name will be changed.
Now we have to go to Site 2 and to register the meta fields we are about to update.
add_action( 'rest_api_init', function(){
register_meta( 'user', 'city', array(
'type' => 'string',
'single' => true,
'show_in_rest' => true
) );
register_meta( 'user', 'age', array(
'type' => 'integer',
'single' => true,
'show_in_rest' => true
) );
} );
Done! Right now we are ready to run our REST API request to change user meta data.

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