How to Show Empty Search Results on WordPress

closeThis post was published 6 years 4 months ago, which is pretty much forever ago in internet time. As such, some of what's discussed here may no longer work as described.
TL;DR: FYI, YMMV
WordPress Logo

WordPress Logo (Photo credit: Phil Oakley)

When one of your users submits an empty search (that is, they click submit without entering anything in the text field), the default behavior for WordPress is to redirect to the home page, and no indication is given that there was a problem with the search. Unfortunately, this is not a user-friendly thing to do. How can we fix this?

Building A More User-Friendly Empty Search in WordPress

Ideally the user would arrive at your search results page, regardless of what they type into the search text field. This would let them know they performed a search successfully, even if no results were found. I’m not going to get into much detail about what to put on that page and how to get it there, but a good option would be to let your users know they need to enter something into the text field if they want to perform a search.

Changing the Default Behavior of WordPress

In order to change the default behavior, we need to understand what that behavior is. WordPress essentially treats an empty search as if no search happened at all. We’re going to tell WordPress that a search did happen so it can direct the user to the search results page. We’ll do this by modifying the $wp_query object before returning results using the pre_get_posts hook.

Add the following code to your functions.php file in your site’s theme:

function allowBlankSearch($query)
{
	global $wp_query;

	// If the search is empty, return true
	if(isset($_GET['s']) && ($_GET['s'] == ''))
	{
		$wp_query->set('s', ' ');
		$wp_query->is_search = true;
	}

	return $query;
}

add_action('pre_get_posts', 'allowBlankSearch');

Now when a user performs an empty search, WordPress will direct them to your website’s search results page.

Leave a reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>