I need to block some accesses to search results not the whole page, just the results.
The problem is, I need the search SQL query to not happen AT ALL. (I can conditionaly hide the output loop template very easily, I’m just not sure SQL is not happening).
Where would I prevent such thing (I assume some filter/action hook I just could not find the right one)?
EDIT: Please note, that the page needs to be loaded and displayed, otherwise I would proceed with request blocking approach like template_redirect
It’s possible to avoid SQL execution in WP_Query
with the posts_pre_query
filter.
It’s e.g. used by plugins to outsource the default search to 3rd party search engines.
Here’s an example how we can override the main search query on the front-end, with an empty posts array and avoid running the SQL search query:
add_filter( 'posts_pre_query', function( $posts, \WP_Query $query ){
if( $query->is_search() && $query->is_main_query() && ! is_admin() ) {
return array();
}
return $posts;
}, 10, 2 );
Since we’re returning an empty array, I don’t think we need to adjust the
$query->found_posts
or $query->max_num_pages
as they are zero by default.