Archived topic
how to fix empty or blank searches from displaying all posts
5 replies · Started by anand on March 12, 2020
any workaround for this
Hi there,
Not quite sure if I understand.
Can you explain a bit more?
I'm not seeing a search in the page you've linked.
Let me know :)
Hi Anand and Leo,
I've noticed this in the past as well. This isn't really a theme issue, but is the default behavior of WordPress. I'm not sure if it's bug or a feature. 😉
I've been using the code below in my functions.php file to halt the query if it is blank.
/**
* Halt the main query in the case of an empty search
*/
add_filter( 'posts_search', function( $search, \WP_Query $q )
{
if( empty( get_search_query() ) && $q->is_search() && $q->is_main_query() )
$search .=" AND 0=1 ";
return $search;
}, 10, 2 );
With the default GeneratePress theme, it should return the standard no-results page.
Hope this helps!
Thank you for this!!
THANKS
works wonderful
returns
Nothing Found
Sorry, but nothing matched your search terms. Please try again with some different keywords.
hi,
This code return empty posts and pages if we try to filter posts in admin dashboard either we filter per category or per date,
I've add this !is_admin() so the code does not mess with the dashboard.
If someone have a better code or better approach to how wordpress handle empty search please share.
/**
* Halt the main query in the case of an empty search
*/
add_filter( 'posts_search', function( $search, \WP_Query $q )
{
if( empty( get_search_query() ) && !is_admin() && $q->is_search() && $q->is_main_query() )
$search .=" AND 0=1 ";
return $search;
}, 10, 2 );