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

Moving the admin search page
Jules Colle came up with a method of moving the Relevanssi admin search page from under the Dashboard heading to…
German umlauts
By default, the search ignores German umlauts. Searching for “uber” will also find “über” and so on. This ignorance is…

Related Posts:

Comment Section:

15 Comments. Leave new

Leave a Reply to Mikko Saari 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