This morning I was trying to write up a custom search results template for WordPress using Twitter’s Bootstrap and run into a strange situation. First, here’s what my custom form’s HTML looked like:
Everything seemed to be working just fine, until I started writing up the code for no search results found. When clicking the submit button without typing any search text, pages and posts would still show up in the results!
After some Googling, I found out that the WordPress team has made this intentional. Their perspective is that some results should at least show up in this case. WordPress hits the home page using HTTP GET and passes your search query to an “s” parameter:
So apparently, when WordPress sees an empty search string it doesn’t even use the “is_search” page handler and that’s why this happens (it actually uses the “is_home” handler instead).
Since my client wanted to simply display no search results in this situation, here’s what I did. First I went to the bottom of my “functions.php” file found in my theme directory and added the following (you can create the file if there isn’t one there already):
This bypassed the standard WordPress behavior and allowed me to send the request along to my theme’s search template (“search.php” file found again under my theme).
Then it was a matter of handling the empty GET parameter in my “search.php” template. Here’s my complete template, keeping in mind that I am using Twitter Bootstrap to style my output:
My template includes some other functions as well, such as custom footer paging and my standard header and footer for the site, which are not important in this example.
13 Responses to How to handle and customize an empty search query in WordPress