Performance PHP Beginner

Turn Off Site Search

Return a 404 for WordPress search results on sites that don't use search, stopping bots from running expensive searches.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 18 lines
add_action( 'template_redirect', function (): void {
	if ( ! is_search() || is_admin() ) {
		return;
	}

	// Keep WooCommerce product search.
	if ( 'product' === get_query_var( 'post_type' ) ) {
		return;
	}

	global $wp_query;
	$wp_query->set_404();
	status_header( 404 );
	nocache_headers();
} );

// Remove the search form from themes that print get_search_form().
add_filter( 'get_search_form', '__return_empty_string' );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.

Every WordPress site answers ?s=anything, and bots love it: each search is a slow database query that caches can’t store. If your site doesn’t have a search box, this snippet turns search off.

How it works

On template_redirect, a search request is turned into a 404 before the theme renders results. WooCommerce product searches, which add post_type=product, still work.

The get_search_form filter hides any search forms printed by your theme or widgets.

Things to watch

  • WordPress still runs the search query before template_redirect. To skip the query entirely, also use pre_get_posts to set 'post__in' => [ 0 ] for searches.
  • Block themes using the Search block print it themselves; remove the block from your templates.

How to test it

Visit yoursite.com/?s=test. You should get your 404 page.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only