I am trying to add the post (pages, posts) excerpt in the wp-json/wp/v2/search get endpoint but this endpoint seems to not take into account the register_rest_field method.
add_action('rest_api_init', function() {
register_rest_field('post', 'excerpt', array(
'get_callback' => function ($post_arr) {
die(var_dump($post_arr));
return $post_arr['excerpt'];
},
));
register_rest_field('page', 'excerpt', array(
'get_callback' => function ($post_arr) {
die(var_dump($post_arr));
return $post_arr['excerpt'];
},
));
});
This causes wp-json/wp/v2/pages and wp-json/wp/v2/posts to die, but wp-json/wp/v2/search works perfectly, although it renders posts and pages.
Any idea how I can add my excerpt to the results of the wp-json/wp/v2/search route?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
For the search endpoint, the object type (the first parameter for register_rest_field()) is search-result and not the post type (e.g. post, page, etc.).
So try with this, which worked for me:
add_action( 'rest_api_init', function () {
// Registers a REST field for the /wp/v2/search endpoint.
register_rest_field( 'search-result', 'excerpt', array(
'get_callback' => function ( $post_arr ) {
return $post_arr['excerpt'];
},
) );
} );
Method 2
Embeds only return fields that have the
embedcontext. You can add embed to the context specified in the schema using the"rest_{$post_type}_item_schema"filter.
— https://core.trac.wordpress.org/ticket/51596
Here’s an example of that. Note that parent fields like content need to have the context added in order for child fields like content.rendered to show up.
add_filter( 'rest_' . POST_TYPE . '_item_schema', function( $schema ) {
$schema['properties']['content']['context'][] = 'embed';
$schema['properties']['content']['properties']['rendered']['context'][] = 'embed';
return $schema;
} );
That feels a bit more “correct” to me than using register_rest_field().
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0