Skip to main content

Fixing empty or blank searches from displaying all posts in WordPress

After creating my own WordPress theme, I needed a search page. I created “search.php” (as that is the template that WordPress recognises to display search results). After testing, I noticed if I hit the submit button without entering a search query, all of the posts on my website will display. Obviously, this isn’t good and after looking online have found a fix to show you.

This code goes in your search.php template



<?php if (have_posts() && strlen( trim(get_search_query()) ) != 0 ) : while (have_posts()) : the_post(); ?>

      <a href="<?php the_permalink();?>">
<h4><?php the_title();?></h4>

</a>
<?php the_excerpt();?>
<hr>


      <?php endwhile; else:?>


<h3>No results match your search.</h3>


<?php endif; ?>



This code goes in your functions.php



 function SearchFilter($query) {
    // If 's' request variable is set but empty
    if (isset($_GET['s']) && empty($_GET['s']) && $query->is_main_query()){
        $query->is_search = true;
        $query->is_home = false;
    }
    return $query;}
add_filter('pre_get_posts','SearchFilter');

Now that you have this in place, any empty search will assume that nothing exists, rather than displaying all results, it will display none.

5 thoughts to “Fixing empty or blank searches from displaying all posts in WordPress”

  1. Nice! I might even suggest using this line instead, so that 1-character searches don’t waste time, either:

    1 ) : while (have_posts()) : the_post(); ?>

    2-character searches could be equally wasteful, in many cases. 🙂

  2. Thank you for the post. In my case i did not want to leave the page to display nothing found. I simply copied the searchform,php file into my child theme folder and set search field attribute to required. This alerts you that must type in a value in the field, and stays on the same page.

    <input type="text" name="s" placeholder="Search" value="” required>

Leave a Reply