Disable Search

This code snippet provides a way to completely disable search functionality on a WordPress website. It might be helpful for specific types of websites where search is not necessary or it might lead to undesired results or performance issues.

This script performs the following actions:

  1. It prevents search queries from executing on the front end. If a user somehow tries to access a search URL, they are redirected to a 404 page.
  2. It unregisters the Search Widget, making it unavailable for use.
  3. It removes the default search form.
  4. It unregisters the core search block, disabling the search block in the Gutenberg editor.
  5. It removes the search box from the WordPress admin bar.

Add this code to your theme’s functions.php file to disable search on your WordPress site. Always remember to test code changes in a staging or local environment before implementing them on a live website.

PHP
// Prevent search queries.
add_action(
	'parse_query',
	function ( $query, $error = true ) {
		if ( is_search() && ! is_admin() ) {
			$query->is_search       = false;
			$query->query_vars['s'] = false;
			$query->query['s']      = false;
			if ( true === $error ) {
				$query->is_404 = true;
			}
		}
	},
	15,
	2
);
// Remove the Search Widget.
add_action(
	'widgets_init',
	function () {
		unregister_widget( 'WP_Widget_Search' );
	}
);
// Remove the search form.
add_filter( 'get_search_form', '__return_empty_string', 999 );
// Remove the core search block.
add_action(
	'init',
	function () {
		if ( ! function_exists( 'unregister_block_type' ) || ! class_exists( 'WP_Block_Type_Registry' ) ) {
			return;
		}
		$block = 'core/search';
		if ( WP_Block_Type_Registry::get_instance()->is_registered( $block ) ) {
			unregister_block_type( $block );
		}
	}
);
// Remove admin bar menu search box.
add_action(
	'admin_bar_menu',
	function ( $wp_admin_bar ) {
		$wp_admin_bar->remove_menu( 'search' );
	},
	11
);