我一直在尝试搜索是否可以通过以下方式在添加一些自定义字段时使用“嵌套”JSON响应register_rest_field
我有以下代码:
function video_get_post_meta($object, $field_name, $request){
return get_post_meta($object[\'id\'], $field_name, true);
}
function video_update_post_meta($value, $object, $field_name){
return update_post_meta($object[\'id\'], $field_name, $value);
}
add_action(\'rest_api_init\', function(){
register_rest_field(\'post\', \'length\',
array(
\'get_callback\' => \'video_get_post_meta\',
\'update_callback\' => \'video_update_post_meta\',
\'schema\' => null
)
);
register_rest_field(\'post\', \'file_name\',
array(
\'get_callback\' => \'video_get_post_meta\',
\'update_callback\' => \'video_update_post_meta\',
\'schema\' => null
)
);
register_rest_field(\'post\', \'thumbnail\',
array(
\'get_callback\' => \'video_get_post_meta\',
\'update_callback\' => \'video_update_post_meta\',
\'schema\' => null
)
);
register_rest_field(\'post\', \'video_url\',
array(
\'get_callback\' => \'video_get_post_meta\',
\'update_callback\' => \'video_update_post_meta\',
\'schema\' => null
)
);
});
这会产生如下结果:
"length": "100",
"file_name": "video_test.mp4",
"thumbnail_": "https://example.com/the_thumb.jpg",
"video_url": "https://example.com/media/20180228.mp4",
但我想知道是否有可能将响应格式改为:
"video": {
"length": "100",
"file_name": "video_test.mp4",
"thumbnail_": "https://example.com/the_thumb.jpg",
"video_url": "https://example.com/media/20180228.mp4"
},
SO网友:maheshwaghmare
使用以下代码段
function video_get_post_meta($object, $field_name, $request) {
return array(
\'video\' => array(
‘length’ => get_post_meta($object[\'id\'], ‘length’, true),
‘file_name’ => get_post_meta($object[\'id\'], ‘file_name’, true),
‘thumbnail_’ => get_post_meta($object[\'id\'], ‘thumbnail_’, true),
‘video_url’ => get_post_meta($object[\'id\'], ‘video_url’, true),
));
}
add_action(\'rest_api_init\', function() {
register_rest_field(\'post\', \'video\',
array(
\'get_callback\' => \'video_get_post_meta\',
\'update_callback\' => \'video_update_post_meta\',
\'schema\' => null
)
);
}
输出应为
"video": {
"length": "100",
"file_name": "video_test.mp4",
"thumbnail_": "https://example.com/the_thumb.jpg",
"video_url": "https://example.com/media/20180228.mp4"
},