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
1 Answer
Reset to default -1For 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.