用户REST API的响应中的元字段是什么?

时间:2021-09-24 作者:jeffinter

我使用此命令发送到API:

curl -X \'GET\' \\
  \'https://www.domain.com/wp-json/wp/v2/users/14?context=view\' \\
  -H \'accept: application/json\' \\
  -H \'authorization: Basic SmVmZnJleTpCdW1ibGViZWUwNjA0\'
我得到的回答是:


{
  "id": 14,
  "name": "User",
  "url": "",
  "description": "",
  "link": "https://www.domain.com/author/User/",
  "slug": "User",
  "avatar_urls": {
    "24": "https://secure.gravatar.com/avatar/",
    "48": "https://secure.gravatar.com/avatar/",
    "96": "https://secure.gravatar.com/avatar/"
  },
  "meta": [],
  "_links": {
    "self": [
      {
        "href": "https://www.domain.com/wp-json/wp/v2/users/14"
      }
    ],
    "collection": [
      {
        "href": "https://www.domain.com/wp-json/wp/v2/users"
      }
    ]
  }
}
有人知道;元(&Q):[]字段是?如果它是用户的元数据,那么如何使用它?

1 个回复
最合适的回答,由SO网友:Maulik Paddharia 整理而成

查看register\\u rest\\u field()以向rest api注册meta。

add_action( \'rest_api_init\', \'adding_user_meta_rest\' );

function adding_user_meta_rest() {
   register_rest_field( \'user\',
                        \'collapsed_widgets\',
                         array(
                           \'get_callback\'      => \'user_meta_callback\',
                           \'update_callback\'   => null,
                           \'schema\'            => null,
                            )
                      );
}
然后将get\\u user\\u元位放入回调中。

   function user_meta_callback( $user, $field_name, $request) {
       return get_user_meta( $user[ \'id\' ], $field_name, true );
   }
WP\\u REST\\u Meta\\u Fields类也可以提供更有用的见解。

答案副本来自-Getting user meta data from WP REST API