How to trim white space in search terms?

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?

Topic request-filter filters Wordpress search

Category Web


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;
  }

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.