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?

  • Have you read the official REST API Handbook yet? The linked resource covers exactly this – kero Jul 25 '18 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 Nov 24 at 0:25
-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.

| improve this answer | |
  • You can get it within the _embedded part of the response when you use the _embed query parameter, so you don't need to modify the response. Explained more in the handbook. – birgire Jan 25 '19 at 14:22
  • This code will break plugins and the post editor – Tom J Nowell Nov 24 at 0:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.