最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

categories - REST API: Display Category names in JSON?

programmeradmin0浏览0评论

Using the Wordpress REST API, I retrieve all my posts into a Angular 6 service. The category field in the JSON displays the ID of the category as an array of numbers.

"category": [ 6 ],

Is there a way, hopefully on the Wordpress end, to have the API use the category name instead? Or add another node to the JSON?

Using the Wordpress REST API, I retrieve all my posts into a Angular 6 service. The category field in the JSON displays the ID of the category as an array of numbers.

"category": [ 6 ],

Is there a way, hopefully on the Wordpress end, to have the API use the category name instead? Or add another node to the JSON?

Share Improve this question asked Jul 25, 2018 at 13:02 SteveSteve 3139 silver badges21 bronze badges 2
  • Have you read the official REST API Handbook yet? The linked resource covers exactly this – kero Commented Jul 25, 2018 at 13:17
  • Doing this as literally requested would cripple existing code that uses the REST API as it expects IDs it can then pass to the category endpoint – Tom J Nowell Commented Nov 24, 2020 at 0:25
Add a comment  | 

1 Answer 1

Reset to default -1

For my needs, I customized the wp rest posts callback:

function get_all_posts( $data, $post, $context ) {
    return [
        'id'        => $data->data['id'],
        'date'      => $data->data['date'],
        'date_gmt'  => $data->data['date_gmt'],
        'modified'  => $data->data['modified'],
        'title'     => $data->data['title']['rendered'],
        'content'   => $data->data['content']['rendered'],
        'excerpt'   => $data->data['excerpt']['rendered'],
        'category'  => get_the_category_by_ID( $data->data['categories'][0] ),
        'link'      => $data->data['link'],


    ];
}
add_filter( 'rest_prepare_post', 'get_all_posts', 10, 3 );

Category endpoint returns directly the name of the post category.

发布评论

评论列表(0)

  1. 暂无评论