wordpresssearch

Wordpress - Disable Search Function


I've added the following code to functions.php to disable archived/crawled/url searching on my wordpress site for performance reasons:

function disable_search( $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', 'disable_search' );
add_filter( 'get_search_form', create_function( '$a', "return null;" ) );

This works perfectly to prevent searching, but also prevents searching for posts in the admin area.

Is there a way to disable searches for users but still allow the admins to search?

Currently, my workaround is to remove this code, perform my necessary search, then paste it back.


Solution

  • Did you try is_admin function? It will return true if the Dashboard or the administration panel is attempting to be displayed. So put this function to your code, it will not fire in Dashboard:

    function disable_search($query, $error = true)
    {
        if (is_search() && !is_admin()) {
            $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', 'disable_search');
    add_filter('get_search_form', '__return_null');
    

    Or:

    function disable_search($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;
        }
    }
    
    if(!is_admin()){
        add_action('parse_query', 'disable_search');
        add_filter('get_search_form', '__return_null');
    }