Posted on 1 Comment

WordPress search redirects to home when search query is empty

Wordpress Logo

By default, WordPress redirects users with empty search queries to the home page – which might not be what you are looking for.

To overcome this behavior and redirect users to the search results page regardless of empty search queries we need to adjust the way WordPress processes search queries. As always, this can be done via functions.php:

function searchRequestFilter( $query_vars ) {
    if( isset( $_GET['s'] ) && empty( $_GET['s'] ) ) {
        $query_vars['s'] = " ";
    return $query_vars;

add_filter( 'request', 'searchRequestFilter' );

As you can see we simply add a filter named searchRequestFilter that intercepts search requests and checks for empty queries. In order to prevent recursion we replace the empty search query with a single space character (” “).

Finally, we need to adjust our search form to handle “empty” search queries, i.e. by removing the forced space from functions.php, like so:

<form class="searchform" 
      action="<?php echo esc_url(home_url('/')); ?>">
    <label for="s" class="searchLabel assistive-text"><?php echo icl_t('Search', 'Search', 'Search'); ?></label>
    <input type="text" class="search-query" name="s" value="<?php echo trim(esc_attr(get_search_query())); ?>" id="s" placeholder="">

That’s it! This way your users are able to submit empty search queries and are still redirected to the search results page.