首页 > 解决方案 > 使用 wordpress REST API 获取搜索片段

问题描述

我有一个使用无头 WP 设置的 NextJS 站点。所以我使用 axios 来获得一些效果很好的搜索结果,但是......它只返回一些信息。

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

我正在使用这个端点:http://headlesswp.local/wp-json/wp/v2/search?search= + e.target.value

无论如何要返回更多数据。特别是搜索结果找到的文本片段。就像谷歌本质上是如何做到的一样。因此搜索“Lorem Ipsum”将返回另一个值,例如:

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

干杯

标签: wordpressrest

解决方案


您可以尝试将custom-search-result.php以下内容放在插件文件夹中,并在管理门户中启用它。

自定义搜索结果.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 );
} );

推荐阅读