admin管理员组文章数量:1278860
I'm seeing a weird problem where if someone searches "Test Search" it's returning fine, but if someone searches "Test Search " it's returning some weird posts that don't seem relevant.
How do I go about trimming white space from beginning and end of a search term?
I'm seeing a weird problem where if someone searches "Test Search" it's returning fine, but if someone searches "Test Search " it's returning some weird posts that don't seem relevant.
How do I go about trimming white space from beginning and end of a search term?
Share Improve this question edited Jul 13, 2018 at 17:09 cjbj 15k16 gold badges42 silver badges89 bronze badges asked Jul 13, 2018 at 15:59 CoreyCorey 3217 silver badges17 bronze badges2 Answers
Reset to default 1I came across the same problem.
In my opinion, this should be the default search behavior in WP.
The solution is to filter the array of parsed query variables.
See the documentation here.
Add this to the functions.php
file in your theme directory.
add_filter('request', function ($query_vars) {
if (!is_admin() && !empty($query_vars['s'])) {
$query_vars['s'] = trim($query_vars['s']);
}
return $query_vars;
});
In WordPress search terms are handled as query variables. This means that the request
filter is available to change the variable before the actual database query. Like this:
add_filter ('request', 'wpse308466_filter_search_query');
function wpse308466_filter_search_query ($request) {
if (!is_admin) { // only do this on the front end
ltrim ($request['s']); // strip all whitespaces from beginning of string
rtrim ($request['s']); // strip all whitespaces from end of string
}
return $request;
}
本文标签: filtersHow to trim white space in search terms
版权声明:本文标题:filters - How to trim white space in search terms? 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741267791a2368808.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论