MomasVII
MomasVII

Reputation: 5071

Use wordpress REST API to get search snippet

I have a NextJS site that uses a headless WP set-up. So I am using axios to get some search results which works well but...It only returns a few bits of information.

id: 67
subtype: "page"
title: "Test Title"
type: "post"
url: "http://urlhere.com"

I am using this endpoint: http://headlesswp.local/wp-json/wp/v2/search?search= + e.target.value

Is there anyway to return more data. Specifically the snippet of text that the search results has found. Just like how Google does it essentially. So searching "Lorem Ipsum" will return another value like:

snippet: "...Lorem ipsum dolor sit amet, consectetur adipiscing elit..."

Cheers

Upvotes: 0

Views: 670

Answers (1)

emptyhua
emptyhua

Reputation: 6692

You could try to place the custom-search-result.php below to the plugins folder, and enable it at admin portal.

custom-search-result.php

<?php
/**
 * Plugin Name: Custom search result
 * Description: Custom search result
 * Author:      Emptyhua
 * Version:     0.1
 */

function my_rest_filter_response($response, $server, $request) {
    if ($request->get_route() !== '/wp/v2/search') return $response;
    if (is_array($response->data)) {
        foreach ($response->data as &$post) {
            if (!is_array($post)) continue;
            if ($post['type'] !== 'post') continue;
            $full_post = get_post($post['id'], ARRAY_A);
            if ($full_post['post_content']) {
                $content = preg_replace('/\n\s+/', "\n", rtrim(html_entity_decode(strip_tags($full_post['post_content']))));
                $post['content'] = $content;
            }
        }
        unset($post);
    }
    return $response;
}

add_action( 'rest_api_init', function () {
    add_filter( 'rest_post_dispatch', 'my_rest_filter_response', 10, 3 );
} );

Upvotes: 2

Related Questions