wordpress - 使用 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..."
干杯
解决方案
您可以尝试将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 );
} );
推荐阅读
- vue.js - NuxtJS 中如何将数据从父级传递给子级
- design-patterns - 状态模式与多态性
- html - 无法设置表格大小和滚动
- php - 将可见 URL 更改为另一个
- asp.net-identity - 在 ASP.net Core 3 身份中配置密码要求不起作用
- node.js - MongoDB 播种和复制
- coldfusion - 使用 cfhtmltopdf 在 Coldfusion 中生成 PDF 时出错
- fpga - FPGA 软 IP 内核:它们通常总是依赖于芯片还是独立于芯片
- google-apps-script - 在不触发日历触发器的情况下创建或修改事件
- python - 在 Web_Scrapping 列表返回空列表