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!

Related Questions

Adding microdata using Structured Data Markup Helper HTML

1  Asked on December 6, 2020 by desislava-angelova


Server timeout error on every weekend

0  Asked on December 6, 2020 by dhaval-joshi


How do I make a shortcode to display the shop name on Dokan?

1  Asked on December 5, 2020 by sean-taylor


Excess dependencies

1  Asked on December 5, 2020 by lovor


A conditional button

1  Asked on December 3, 2020 by aashish-tripathi


Visual editor not saving data

0  Asked on December 2, 2020 by jasierok


WordPress Register Form

0  Asked on November 30, 2020


New post status for custom post type

3  Asked on November 30, 2020 by dclawson


Showing related post for custom taxonomy

1  Asked on November 28, 2020 by luca


How to hide “Change role to” dropdown on Users admin menu

0  Asked on November 27, 2020 by rijal-islami


Colliding custom permalink rules

0  Asked on November 26, 2020 by laurent


how to redirect the link to a category in the website

1  Asked on November 26, 2020 by jeline


Custom payment gateway issue

1  Asked on November 26, 2020 by klevis-miho


Ask a Question

Get help from others!

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