From 798e148d7d35e177b8a168cb93362f90750cc048 Mon Sep 17 00:00:00 2001 From: Xavier Zalawa Date: Tue, 3 Jan 2017 23:17:34 +0100 Subject: [PATCH] Return no result for empty search queries --- includes/search.php | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/includes/search.php b/includes/search.php index 4c096b1..973749e 100644 --- a/includes/search.php +++ b/includes/search.php @@ -138,4 +138,25 @@ function thistle_highlight_search_terms( $text ) { add_filter( 'the_excerpt', 'thistle_highlight_search_terms', 999 ); add_filter( 'the_content', 'thistle_highlight_search_terms', 999 ); + if ( ! function_exists( 'thistle_handle_empty_search_query' ) ) { + /** + * Short-circuits the search query for that returns no result + * if there is not searched term. + * + * By default, WordPress returns all results if there is not searched term. + * This behaviour has no sense. + * + * @param string $where The WHERE clause of the query. + * @param WP_Query $wp_query The WP_Query instance (passed by reference). + * @return string + */ + function thistle_handle_empty_search_query( $where, $wp_query ) { + if ( $wp_query->is_main_query() && $wp_query->is_search() && empty( $wp_query->query_vars['s'] ) ) { + $where = ' AND 0=1'; + } + + return $where; + } + } + add_filter( 'posts_where_request', 'thistle_handle_empty_search_query', 10, 2 ); }