WordPress Empty Search Template

WordPress provides you with a nice and easy way to style the search page template using the search.php in your theme. However there is something that is relatively strange related to the searches in WordPress.

If somebody hits the search button without having the search field filled in it gives you the blog archieve template using the index.php. (this is when openinig example.com/?s=)

Solution to this problem is just to tell wordpress that it’s a search (so is_search becomes true) if the s parameter is set but is empty. This should happen on a hook before the posts are requested.

So in your functions.php you can simply put this code

/* Fix for empty search redirect to index.php */
function shtrakeu_fix_empty_search ($query){
  global $wp_query;
  if (isset($_GET['s']) && empty($_GET['s'])){
    $wp_query->is_search=true;
  }
  return $query;
}
add_action('pre_get_posts','shtrakeu_fix_empty_search');

Cheers and follow me on twitter @ninarski

One Reply to “WordPress Empty Search Template”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.