When you request posts using WP API’s search mechanism, it returns tags as one of the post’s properties, but it is an array of tag IDs, not tag names. Is there a way to make the API include the name of the tags without making subsequent requests to the API by tag ID for each one?
tags: [
188,
30,
151,
189
]
I couldn’t find any parameter in the API docs that does this, so I was thinking of creating a custom plugin to maybe filter and substitute the tag ID’s for names before the response is sent back to the API caller. In that case, what action should I listen for?
I figured something out based on what I found at this post.
Basically I need a plugin that listens for when the REST response is about to go out. The plugin code would be similar to the following:
function ag_filter_post_json($response, $post, $context) {
$tags = wp_get_post_tags($post->ID);
$response->data['tag_names'] = [];
foreach ($tags as $tag) {
$response->data['tag_names'][] = $tag->name;
}
return $response;
}
add_filter( 'rest_prepare_post', 'ag_filter_post_json', 10, 3 );
It adds the tag names as a new property called tag_names
. The rest of the heavy lifting is done by the wp_get_post_tags
function.