Adding post fields in wp-json/wp/v2/search

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?

2 Answers
2

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'];
        },
    ) );
} );

Leave a Comment