Category and Term Names in REST API Responses
Adds a "term_names" field to REST API responses for posts and custom post types, so apps get category and tag names without extra requests.
Opens WPIDE on
Code
add_action( 'rest_api_init', function () {
$types = get_post_types( array( 'show_in_rest' => true, 'public' => true ) );
register_rest_field( array_values( $types ), 'term_names', array(
'get_callback' => function ( $object ) {
$names = array();
foreach ( get_object_taxonomies( $object['type'] ?? '', 'objects' ) as $taxonomy ) {
if ( ! $taxonomy->show_in_rest ) {
continue;
}
$terms = get_the_terms( (int) $object['id'], $taxonomy->name );
$names[ $taxonomy->name ] = ( $terms && ! is_wp_error( $terms ) ) ? wp_list_pluck( $terms, 'name' ) : array();
}
return $names;
},
'schema' => array( 'description' => 'Term names keyed by taxonomy.', 'type' => 'object', 'context' => array( 'view', 'edit' ), 'readonly' => true ),
) );
} );
Notes
Only taxonomies shown in REST are included.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.