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?

2 Answers 2


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;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.