How to show blank search on wordpress

By default, wordpress do not search for blank. It redirects to the home page for blank search. To prevent this we can use pre_get_posts hook. We can use pre_get_posts action to manipulate the query variables for specific pages. We can modify $wp_query object before any results are returned. In this example, we are using pre_get_posts before $wp_query returning false value. Use the following code on functions file inside your theme.

<?php
function make_blank_search ($query){
	global $wp_query;
	if (isset($_GET['s']) && $_GET['s']==''){  //if search parameter is blank, do not return false
		$wp_query->set('s',' ');
		$wp_query->is_search=true;
	}
	return $query;
}
add_action('pre_get_posts','make_blank_search');
?>

Comments

comments

5 Comment

  1. Greaaaaat post! That’s why I always say: freelancers are the heart of web evolution! It helped me a lot and I didn’t find anything about make WP return results with empty query around internet, even on WP documentation.

    Regards.

    1. vinay says: Reply

      Thanks joao.

  2. Ben says: Reply

    This was extremely helpful, but I noticed is_home() is still returning true. so i added the line:

    $wp_query->is_home=false;

    I suspect it’s possible that other is_***() also return the incorrect value but for me this fixed an issue.

  3. Doda says: Reply

    It looks very helpful, but I don’t know where to paste this? In which file?

    1. vinay says: Reply

      Hi Doda,
      You can paste the code on functions.php inside your theme file.

Leave a Reply