简体   繁体   中英

How To Use WordPress Rest API v2 Update User Meta

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"}]}

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 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM