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