您需要修改REST API響應內容 - 它可以包含您想要的信息。
這是我的例子之一,其中我想包括自定義字段值:
add_action('rest_api_init', 'slug_register_embed_youtube');
// "venue" is a custom post type I created using the WP Types plugin
function slug_register_embed_youtube() {
// first register the field with WP REST API
register_rest_field('venue',
'meta_data',
array(
'get_callback' => 'venue_get_meta',
'update_callback' => null,
'schema' => null,
)
);
}
function venue_get_meta($post, $field_name, $request) {
// I wanted the value to appear in the response as "youtube_embed",
// and I wanted the "wpcf-youtube-embed" custom field's value there
$meta_data = array(
'youtube_embed' => get_post_meta($post[ "id" ], 'wpcf-youtube-embed')[ 0 ],
);
return $meta_data;
}
上面的代碼修改的響應:
{
"id": 20,
"date": "2016-06-08T16:37:23",
"date_gmt": "2016-06-08T16:37:23",
"guid": {
"rendered": "http://www.example.com/wp/?post_type=venue&p=20"
},
"modified": "2016-06-20T11:45:22",
"modified_gmt": "2016-06-20T11:45:22",
"slug": "aquarium-club",
"type": "venue",
"link": "http://www.example.com/wp/venue/aquarium-club/",
"title": {
"rendered": "Aquarium Club"
},
"content": {
"rendered": "<p>Aquarium Club. That’s OK. 7765e546uzfkjglh</p>\n<p> </p>\n<style>\n.gmap-iframe-container {\nmax-width: 100%;\n}\n.gmap-iframe {\nwidth: 100%;\nheight: 200px;\nmin-width:100%;\n}\n</style>\n<div class=\"gmap-iframe-container\">\n<iframe src=\"https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d2695.565888030695!2d19.052103115616678!3d47.49836967917771!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x4741dc402a04eee3%3A0x6869564cd433693c!2sAkv%C3%A1rium+Klub!5e0!3m2!1shu!2shu!4v1466147278469\" frameborder=\"0\" style=\"border:0\" allowfullscreen class=\"gmap-iframe\"></iframe></p>\n"
},
"excerpt": {
"rendered": "<p>Aquarium Club. That’s OK. 7765e546uzfkjglh </p>\n"
},
"featured_media": 0,
"menu_order": 0,
"format": "standard",
"tags": [],
"meta_data": {
"youtube_embed": "https://www.youtube.com/embed/xBW7DglTDGs"
},
"_links": {
"self": [
{
"href": "http://www.example.com/wp/wp-json/wp/v2/venue/20"
}
],
"collection": [
{
"href": "http://www.example.com/wp/wp-json/wp/v2/venue"
}
],
"about": [
{
"href": "http://www.example.com/wp/wp-json/wp/v2/types/venue"
}
],
"wp:attachment": [
{
"href": "http://www.example.com/wp/wp-json/wp/v2/media?parent=20"
}
],
"wp:term": [
{
"taxonomy": "post_tag",
"embeddable": true,
"href": "http://www.example.com/wp/wp-json/wp/v2/tags?post=20"
}
],
"curies": [
{
"name": "wp",
"href": "https://api.w.org/{rel}",
"templated": true
}
]
}
},
注意,我有此
"meta_data": {
"youtube_embed": "https://www.youtube.com/embed/xBW7DglTDGs"
},
「tags」數組之後。
你可以找到修改WP REST API V2這裏響應的所有信息:http://v2.wp-api.org/extending/modifying/
那正是我想要的,但在那裏我應該寫的代碼? –
我把它放在functions.php中。實際上,使用add_action()時,它不是真的/只在「位置」中,而是在WP調用文件時執行的「函數順序」中。由於每次刷新頁面時都會調用主題的function.php,因此每次刷新頁面(當然還有每個REST API查詢)時,代碼都會在那裏。 –
非常感謝你 –