WordPress
After many years, while working on a new project, I noticed that searches on WordPress sites with an empty search query return every searchable, published item from the posts table instead of no results.
This doesn’t seem correct—an empty search should return no results.
Doing a web search for the problem, most answers suggest modifying the search query with $query->set('post__in', array(0));
. This doesn’t work. The results still contain everything.
The post__in
array needs one small change to work; switch the 0
to a -1
.
Add the final function to functions.php
:
function mysite_empty_search_term_results($query)
{
$search_query = trim(get_search_query());
if (!is_admin() && $query->is_main_query() && $query->is_search() && empty($search_query)) {
$query->set('post__in', array(-1));
}
}
add_action('pre_get_posts', 'mysite_empty_search_term_results');
Code language: PHP (php)