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

Using Relevanssi without a search term
Deprecated: Relevanssi has long supported searching without a search term. These instructions are not necessary. Version 1.7.3 introduces the possibility…
Search shortcode
Relevanssi adds a shortcode to help making links to search results. That way users can easily find more information about…

Related Posts:

Comment Section:

15 Comments. Leave new

Leave a Reply to Nick Woods 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