Empty search input returns all posts

Just an alternative to the informative answer by @PieterGoosen.

After Pieter posted this part:

if ( ! empty( $q['s'] ) ) {
    $search = $this->parse_search( $q );
}

it came to mind that it might be possible to re-parse the search query, within the posts_search filter, for empty search string. But the parse_search() method is protected and even if we could access it, the empty search would just give us:

AND (((wp_posts.post_title LIKE '%%') OR (wp_posts.post_content LIKE '%%'))) 

and that would just search for everything. So that path wasn’t fruitful 😉

In WordPress 4.5 it has changed to

if ( strlen( $q['s'] ) ) {
    $search = $this->parse_search( $q );
}

Instead we could try to halt the main query, in the case of an empty search:

/**
 * Halt the main query in the case of an empty search 
 */
add_filter( 'posts_search', function( $search, \WP_Query $q )
{
    if( ! is_admin() && empty( $search ) && $q->is_search() && $q->is_main_query() )
        $search .=" AND 0=1 ";

    return $search;
}, 10, 2 );

Leave a Comment