0
votes

I am using WordPress 4.8 and trying to update user meta field using rest api built-in. I can update other fields of user but not the meta field of user. I try to POST the following json body to server, but i got no update at all. Hope anyone can show me some example how to do a post request to update user's meta field.

URL : http://example.com/wp-json/wp/v2/users/100  
method : POST 
content-type: application/json 
body : {"meta":{"meta_key":"meta_value"}} or {"meta": {"key":"meta_key","value":"meta_value"}} or {"meta":[{"meta_key":"meta_value"}]} or {"meta":[{"key":"meta_key","value":"meta_value"}]}
1
Did you figure out? - Lincoln Lemos

1 Answers

0
votes

I was able to solve this by registering the meta value that I wanted to update through the API:

register_meta('user', 'my_meta_value_name', [ 'type' => 'string', 'single' => true, 'show_in_rest' => true, ]);

And then with JavaScript we can update it like:

var currentUserId = 1; var apiUrl = '/wp-json/wp/v2/users/' + currentUserId; var data = { 'id': currentUserId, 'meta': { 'my_meta_value_name': 'new value' } }; $.ajax({ method: 'POST', url: apiUrl, headers: {'X-WP-Nonce': 'nonce_value_here'}, data: data }) .success(function (data) { // do stuff }) .fail(function (data) { // do stuff });