Return a 404 for WordPress search results on sites that don't use search, stopping bots from running expensive searches.
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' );
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.
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.
template_redirect. To skip the query entirely, also use pre_get_posts to set 'post__in' => [ 0 ] for searches.Visit yoursite.com/?s=test. You should get your 404 page.