WordPress provides a search functionality which can be embedded in your WordPress installation. That search functionality may not be needed always.
If you have a website with a single or only a few pages, the search feature is redundant. In that case, we can simply disable this feature to make things simple and clean.
The WordPress search can be implemented either as a WordPress widget or by coding with the theme specific template elements. If the search component is deployed by using the WordPress widget, then it can be removed from the UI by using the admin panel.
If you designed the site search with your custom code instead of using WordPress widget, then you have to control its display by using programming and CSS. But, it is all about the UI display and not about disabling the feature as whole to prevent accessing search anyway.
For disabling search, we need to write few lines of code in our theme or child theme‘s functions.php. In this post, I have shown how to disable the search feature by programming with the theme files.
I have added hooks to disable search access and to remove the search component from the UI.
This code block contains a function to disable the search access and shows the Page not Found. This function will be hooked with the appropriate tags specifying the action to be performed.
<?php
...
//function search_filter_query( $query, $error = true ) {
if ( is_search() ) {
$query->is_search = false;
$query->query_vars[s] = false;
$query->query[s] = false;
// to error
if ( $error == true )
$query->is_404 = true;
}
}
add_action( 'parse_query', 'search_filter_query' );
...
?>
After disabling the search by setting the search query properties to false, a WordPress filter hook is added to remove the search component from the UI.
Caution: create_function is a PHP built-in function which is deprecated as of 7.2.0.
So, I have also specified the alternate code to remove the search widget by using WordPress unregister_widget() method. I have added an action hook to call this unregister method while initializing widgets.
// Caution: create_function is deprecated
add_filter( 'get_search_form', create_function( '$a', "return null;" ) );
// OR
function hide_search_widget() {
unregister_widget('WP_Widget_Search');
add_action( 'widgets_init', 'hide_search_widget' );