使用WordPress REST API获取搜索摘要(无头WP+NextJS场景)
解决方案
你当前使用的 WordPress 默认搜索端点 /wp/v2/search 本身设计仅返回基础元字段,要获取搜索摘要以及更多自定义字段,有两种成熟方案:
方案1:修改WP端REST响应(推荐,性能最优)
直接在 WordPress 侧扩展搜索接口的返回字段,不需要调整前端原有调用逻辑,接口性能也不会有明显损耗。
将以下代码加入 WordPress 主题的 functions.php 文件,或者自定义功能插件中即可:
add_filter('rest_prepare_search_result', function($response, $post, $request) { // 获取用户提交的搜索关键词 $search_keyword = $request->get_param('search'); if (empty($search_keyword)) return $response; // 获取对应文章/页面的纯文本内容 $post_content = get_post_field('post_content', $response->data['id']); $plain_content = wp_strip_all_tags($post_content); $plain_content = preg_replace('/\s+/', ' ', trim($plain_content)); // 定位关键词位置,截取前后文本生成搜索摘要 $keyword_pos = stripos($plain_content, $search_keyword); if ($keyword_pos !== false) { // 截取关键词前后各50字符,总长控制在150字符左右 $start = max(0, $keyword_pos - 50); $snippet = substr($plain_content, $start, 150); // 高亮匹配到的关键词 $snippet = preg_replace('/' . preg_quote($search_keyword, '/') . '/i', '<strong>$0</strong>', $snippet); // 边界补省略号 $snippet = ($start > 0 ? '...' : '') . $snippet . ($start + 150 < strlen($plain_content) ? '...' : ''); } else { // 未匹配到关键词则返回默认摘要 $snippet = wp_trim_words($plain_content, 30, '...'); } // 将摘要字段插入返回结果 $response->data['snippet'] = $snippet; return $response; }, 10, 3);
添加完成后直接调用原有接口即可拿到 snippet 字段,如果你还需要返回特色图、发布时间、分类标签等其他字段,都可以在这个过滤器中把对应内容赋值到 $response->data 中即可。
方案2:前端二次查询(无需修改WP代码,适合无后台权限场景)
如果暂时没有修改 WordPress 后台代码的权限,可以利用现有搜索结果返回的 id 和 subtype 字段,二次调用对应内容接口获取完整信息:
- 单条内容查询接口格式:
http://headlesswp.local/wp-json/wp/v2/{subtype}/{id} - 前端可以用
Promise.all批量处理所有搜索结果的二次查询,拿到content.rendered字段后自行处理摘要截取逻辑即可 - 该方案会额外发起和搜索结果数量相等的请求,性能远低于方案1,仅适合临时调试使用
内容的提问来源于stack exchange,提问作者MomasVII
相关产品推荐
相关产品推荐

