WordPress REST 响应仅显示带有 ID 的分类类别



我正在使用WP作为带有ACF en ACF-2-REST插件的无头CMS。我已经为帖子类型添加了类别,当我拨打 GET 电话时,它会向我显示特定帖子的所有信息,包括类别,但只有 ID。如果我想匹配它,我必须再次调用类别以获取该类别的信息(名称、父级等(。

如何在电话发布中显示该信息而不仅仅是 ID?

JSON 现在如何看待/activities 调用:

{
"id":111,
"date":"2020-01-18T15:39:27",
"date_gmt":"2020-01-18T15:39:27",
"guid":{"rendered":"https://url.be/?post_type=activities&p=111"},
"modified":"2020-01-18T15:39:27",
"modified_gmt":"2020-01-18T15:39:27",
"slug":"walking-on-wood",
"status":"publish",
"type":"activities",
"link":"https://url.be/activities/walking-on-wood/",
"title":{"rendered":"Walking on wood"},
"template":"",
"categories":[14,25,13,2,18,21,6,24],
"acf":{...}
}

我想在"类别"中显示的内容,而不仅仅是数字(来自类别调用(

{
"id":3,
"count":1,
"description":"",
"link":"https://url.be/category/duration/lower-than-30-min/",
"name":"< 30 min.",
"slug":"lower-than-30-min",
"taxonomy":"category",
"parent":2,"meta":[],
"acf":[],
"_links":{"self":[{"href":"https://url.be/wp-json/wp/v2/categories/3"}],
"collection":[{"href":"https://url.be/wp-json/wp/v2/categories"}],
"about":[{"href":"https://url.be/wp-json/wp/v2/taxonomies/category"}],
"up":[{"embeddable":true,"href":"https://url.be/wp-json/wp/v2/categories/2"}],
"wp:post_type":[{"href":"https://url.be/wp-json/wp/v2/posts?categories=3"},{"href":"https://url.be/wp-json/wp/v2/activities?categories=3"}],
"curies":[{"name":"wp","href":"https://api.w.org/{rel}","templated":true}]}
}

在互联网上找不到任何解决方案,我如何使用自定义函数操纵该 JSON 的结构,如果有人指出我正确的方向,将不胜感激。谢谢!

如评论部分所述,此问题的解决方案是为 WP REST API 使用自定义终结点方法,并在其中执行额外的查询以获取所需的数据。这样,您可以执行所有数据操作以获得完美的响应,从而产生一个 REST 调用。

摘自官方开发者文档

定义终结点方法并添加一些额外数据

<?php
add_action( 'rest_api_init', function () {
register_rest_route( 'myplugin/v1', '/author/(?P<id>d+)', array(
'methods' => 'GET',
'callback' => 'my_awesome_func', //note that this is the method it will fire
'args' => array(
'id' => array(
'validate_callback' => function($param, $request, $key) {
return is_numeric( $param );
}
),
),
) );

/**
* Grab latest post by an author along with its category!
*
* @param array $data Options for the function.
* @return array Post,
*/
function my_awesome_func( $data ) {
$posts = get_posts( array(
'author' => $data['id'],
) );
if(!empty($posts)) {
//Example of appending extra data
foreach($posts as $post) {
$category = wp_get_post_terms($post->ID, 'category');
$post['category'] = $category; 
}
return $posts;
} else  {
return new WP_Error( 'no_author', 'Invalid author', array( 'status' => 404 ) );
}
}

最新更新