我正在尝试使用JS和WP Rest API更新前端上的自定义post类型元数据。
对象键为wishlist_array
在下面metadata
下面是如何从http://ohalocal.local/wp-json/wp/v2/oha_wishlist
(我的自定义帖子)外观:
{
"id": 1248,
.
.
.
"metadata": {
"wishlist_array": [
""
],
.
.
.
在php上,我设置register_rest_field()
功能如下: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($??, $??, $??);
},
最后是我的fetch()
连接到API的函数。它不会返回错误,例如,如果我尝试更新标题,它会很好地工作。仅当尝试更新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);
});