I am trying to update a custom post type metadata on the front end using JS and the WP Rest API.
The object key is wishlist_array
under metadata
Here is how JSON response from http://ohalocal.local/wp-json/wp/v2/oha_wishlist
(my custom post) looks:
{
"id": 1248,
.
.
.
"metadata": {
"wishlist_array": [
""
],
.
.
.
On php I set the register_rest_field()
function as follow:
register_rest_field('oha_wishlist', 'metadata', array(
'get_callback' => function ($data) {
return get_post_meta($data['id'], '', '');
},
'update_callback' => function ($data) {
// Don't understand how to use the arguments here
// How can I print or log the $data content??
return update_field($??, $??, $??);
},
And finally my fetch()
function where I connect to the API. It returns no error and if I try to update the title, for instance, it works well. Only doesn't when trying to update the metadata
.
fetch("http://ohalocal.local/wp-json/wp/v2/oha_wishlist/1248", {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-WP-Nonce": phpVarObj.nonce
},
body: JSON.stringify({ metadata: { wishlist_array: "add this" } })
})
.then(function(response) {
return response.json();
})
.then(function(wishlistPosts) {
console.log(wishlistPosts);
});