Skip to main contentSkip to footer

If you want to auto-direct the user directly to the result if there’s just one result for the search, that’s quite easy. Add the following code to your site:

add_action( 'template_redirect', 'one_match_redirect' );
function one_match_redirect() {
    if ( is_search() ) {
        global $wp_query;
        if ( 1 === $wp_query->post_count ) {
            wp_redirect( get_permalink( $wp_query->posts['0']->ID ) );
            exit();
        }
    }
}

This is not Relevanssi-specific and works just fine even without Relevanssi. If you are using Relevanssi on a multisite system, you need a small change to the code:

add_action( 'template_redirect', 'one_match_redirect' );
function one_match_redirect() {
    if ( is_search() ) {
        global $wp_query;
        if ( 1 === $wp_query->post_count ) {
            switch_to_blog( $wp_query->posts['0']->blog_id );
            wp_redirect( get_permalink( $wp_query->posts['0']->ID ) );
            exit();
        }
    }
}

The code is originally from WP Beginner.

If you want to redirect particular search terms to posts without going through the search results page, that looks like this:

add_action( 'template_redirect', 'search_term_redirect' );
function search_term_redirect() {
    if ( is_search() ) {
        global $wp_query;
        if ( 'term' === $wp_query->query_vars['s'] ) {
            wp_redirect( 'http://www.example.com/target-page/' );
            exit();
        }
        if ( 'word' === $wp_query->query_vars['s'] ) {
            wp_redirect( 'http://www.example.com/another-target-page/' );
            exit();
        }
    }
}

Your account

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

Search

Popular Resources

Multisite searches
Multisite search only works in Relevanssi Premium. Free Relevanssi can be installed in multisite environments, but it cannot search across…
Toolset Views
Relevanssi works fine with Toolset, thanks to a lot of compatibility code the makers of Toolset have included in it…
Metabox
Metabox is a suite of plugins to handle custom fields. It seems like a solid competitor for Advanced Custom Fields.…

Related Posts:

Comment Section:

15 Comments. Leave new

Leave a Reply to Richard Cancel 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