需求
默认搜索只匹配标题,难以满足内容站需求。本文实现标题+正文模糊搜索,并在搜索框增加热门标签联想。
一、扩大搜索范围
Text
add_filter('posts_search', function ($search, $q) {
if (!$q->is_search() || !$q->is_main_query()) return $search;
global $wpdb;
$term = $wpdb->esc_like($q->get('s'));
$search .= " OR {$wpdb->posts}.post_content LIKE '%{$term}%'";
return $search;
}, 10, 2);
二、搜索框标签联想
在前端监听输入,请求热门标签接口并渲染建议:
Text
input.addEventListener('input', debounce(function () {
fetch('/wp-json/wp/v2/tags?search=' + input.value)
.then(r => r.json())
.then(tags => renderSuggest(tags));
}, 300));
三、搜索词高亮
在结果页高亮命中关键词:
Text
add_filter('the_title', function ($t) {
if (is_search() && get_query_var('s')) {
$t = preg_replace('/('' . preg_quote(get_query_var('s'), '/') . '')/i', '$1', $t);
}
return $t;
});
注意事项
- 全文模糊搜索对大数据集性能有影响,建议加 Sphinx/Elasticsearch 或限制搜索范围。
- 联想接口注意做频率限制。

