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

Wordpress REST response shows taxonomy categories only with ID's

我将 WP 用作带有 ACF en ACF-2-REST 插件的无头 CMS。我已将类别添加到 post-type,当我进行 GET 调用时,它会向我显示特定 post 的所有信息,包括类别,但仅显示 ID。如果我想匹配它,我必须再次调用 Categories 以获取该类别的信息(名称、parent 等)。

如何在 post 调用中显示该信息而不仅仅是 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":{...}
}

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

{
"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}]}
}

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

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

摘自 official developer docs

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

<?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 ) );
  }

}