WP Fix: Blank Search Sends Users to the Homepage

In a recent project I had a problem with the search results page. Basically, when a user clicks on the search button without typing a keyword he or she is brought to the homepage. Rather, the query should be empty and either display the list of result or tell the user that they need to enter a keyword (validation).

How to Fix the Search

After searching the Internets I found a few fixes. Here’s one on the WordPress forums that seemed the most promising. This led me to the code below which, after being added to your theme’s functions.php file, will bring prevent the user from going to homepage and rather display the search results page.

Add to your theme’s functions.php file

add_filter( 'request', 'my_request_filter' );
function my_request_filter( $query_vars ) {
    if( isset( $_GET['s'] ) && empty( $_GET['s'] ) ) {
        $query_vars['s'] = " ";
    }
    return $query_vars;
}

A Few Notes

Blank search results seems to only happen when you have your homepage set to a static page in WordPress rather than the default settings. I haven’t seen any mentions of other configurations causing this on the web.

WordPress DEVs are Aware of the Issue

Here’s a WP Trac ticket opened at WordPress that says as of 2-months ago a fix for this is slated for future WP version 3.3