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 badges
Add a comment  | 

2 Answers 2

Reset to default 1

I 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