TransWikia.com

REST API: Display Category names in JSON?

WordPress Development Asked by Steve on August 3, 2020

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?

One Answer

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.

Answered by cmii on August 3, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP