Posted on

How to block searches without a search term

By default, Relevanssi returns all posts when searching without a search term. That’s the default WordPress behaviour. Sometimes it may not be the wanted behaviour. One reason is performance: returning all results can be very slow.

To stop Relevanssi from running when there’s no search term, add this to your site:

add_filter( 'relevanssi_search_ok', function ( $ok, $query ) {
    if ( empty( $query->query_vars['s'] ) ) {
        $ok = false;
    }
    return $ok;
}, 10, 2 );

This little function will stop Relevanssi from running when there’s no search term specified. It will still leave you with the default WordPress search that returns all the posts. That’s generally faster than Relevanssi.

If you don’t want anything returned when there’s no search term, add this function to stop even the default WP search:

add_filter( 'posts_request', function( $request, $query ) {
    if ( $query->is_search() && $query->is_main_query() && !is_admin() && empty( $query->query_vars['s'] ) ) {
        global $wpdb;
        $request = "SELECT * FROM $wpdb->posts WHERE 1=2";
    }
    return $request;
}, 10, 2 );

Now when you search without a search term, the search should return no results.

2 comments How to block searches without a search term

  1. Hi, I’m the one that asked how to do this by mail. I works, but just found out that it removes all the posts on the blog page too. I added this to conditional in the ‘posts_request’ function to fix this:

    && $query->is_search() && $query->is_main_query() && !is_admin() )

    add_filter( ‘posts_request’, function( $request, $query ) {
    if ( empty( $query->query_vars[‘s’] ) && $query->is_search() && $query->is_main_query() && !is_admin() ) {
    global $wpdb;
    $request = “SELECT * FROM $wpdb->posts WHERE 1=2”;
    }
    return $request;
    }, 10, 2 );

Leave a Reply

Are you a Relevanssi Premium customer looking for support? Please use the Premium support form.

Your email address will not be published. Required fields are marked *