Annoying Behavior of WordPress Search Function

by DJL
0 replies
Re: WordPress 3.6
Twenty Thirteen Theme

This behavior may be different if you are using other WP versions or different themes.

I observed that, if you click the Search button without entering anything in the text input box, WordPress displays results containing the complete text of EVERY post you have published, and does not label the output as "Search Results for...". If you enter one or more spaces in the input box (and nothing else), it returns a slightly different result, containing excerpts of all published posts and pages!

To me, this seems undesirable, so I did some research on the issue.

I found numerous discussions and proposed ways of modifying this behavior, but none of them were quite satisfactory. Some of them were so convoluted that they gave me a headache!

With credit to WebDevSecrets.com, I found what I believe is the simplest solution. I modified the recommended code slightly, and would like to share it here with you:

Add the following code to your theme's functions.php file:

Code:
function allowBlankSearch($query)
{
    global $wp_query;
    // If the search is empty, return true
    if(isset($_GET['s']) && (trim($_GET['s']) == ''))
    {
        $wp_query->set('s', 'nothing-nada-zilch');
        $wp_query->is_search = true;
    }
    return $query;
}
 
add_action('pre_get_posts', 'allowBlankSearch');
With this code installed, a blank search will now return a page saying "Nothing found," which I believe makes the result more meaningful to the user.

If you are using a child theme, in which you may not have a functions.php file, create a new text file with that name, insert the above code, and enclose it between the following two lines:
Code:
<?php

?>
#annoying #behavior #search #wordpress

Trending Topics