Disable default WordPress search query


If you’re going to implement your custom wordpress search (not wordpress native) on search.php template – for example using Google Custom Search or Bing – you might have everything working ok, but wordpress is still performing search queries to database which can slow down your site. This is because wordpress treats search.php template as search page, no matter what is inside and prepares post list before it’s loaded.

So to avoid this, you need to use the following code:

function _cancel_query( $query ) {

	if ( !is_admin() && !is_feed() && is_search() ) {
		$query = false;
	}

	return $query;
}

add_action( 'posts_request', '_cancel_query' );

And to remove search form from that page (probably you won’t need it) you can use following:

add_filter( 'get_search_form', create_function( '$a', "return null;" ) );

This can be embedded to any of your plugin code or functions.php inside your theme.

Join the Conversation

2 Comments

  1. Hey,

    Thanks for this snippet. Unfortunately, in my tests it seems this snippet cancels more than just the default search query. I’m running several custom “new WP_Query($args)” and these also get canceled for some reason.

    Just wondering if there is a way to fix this snippet to work for those cases as well. I tried adding is_main_query() to the if statement, but that did not help either.

    Thanks

Leave a comment

Your email address will not be published. Required fields are marked *