AnswerBun.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!

Related Questions

WordPress admin creation through phpmyadmin not working

2  Asked on December 3, 2021 by taberkinslaw

   

Asking help regarding potential malware

1  Asked on December 3, 2021

   

Buddypress dynamic profile field

1  Asked on December 1, 2021 by marccaps

 

WP_Error could not be converted to string

2  Asked on December 1, 2021 by gamerbanaan

 

How to set subcategory in Woocommerce?

1  Asked on December 1, 2021 by yves-gonzaga

 

Woocommerce get attributes

0  Asked on December 1, 2021 by pierre-max-halldegare

 

Trouble with plugin styles in admin area of WordPress

0  Asked on November 28, 2021 by darth-mikey-d

   

Automatically Add New Tags to Sub-menu

1  Asked on November 28, 2021 by ignas

     

character encoding problem in custom template

1  Asked on November 28, 2021 by dhaval-panchal

   

Mixed unrelated taxonomy in permalink

0  Asked on November 28, 2021 by vauneen

     

Custom Rewrite Rule Removing Query String

2  Asked on November 28, 2021 by appshine

     

Automatically generate pages from SQL

1  Asked on November 26, 2021 by trilobutt

   

Rewrite Page Parameters

1  Asked on November 26, 2021 by kom

     

Ask a Question

Get help from others!

© 2022 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP