Skip to main contentSkip to footer

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.

Your account

Not logged in. Log in to see your license details.

Search

Popular Resources

A New Chapter for Relevanssi
We are very excited to announce that Relevanssi has found a new home with comesio solutions GmbH, a software company…
Oxygen and Ninja Tables
Relevanssi has support both for Oxygen and Ninja Tables, but the way the Ninja Tables support is done, it’s not…

Related Posts:

Comment Section:

2 Comments. Leave new

  • Smeedijzer Internet
    July 7, 2022 12:35 pm

    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 );

    Reply

Leave a Reply

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

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed