WordPress search – redirect on single result

The days of ‘everything should be at most 3 clicks away‘ have gone. Even so, if you want to save your visitors a click, you can automatically redirect them to their result when the WordPress search returns a single hit.

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

The wp_redirect() 302 argument is the default value, but I like to explicitly set it. As popular as 301 redirects are, they really do not suit this scenario.

2 thoughts on “WordPress search – redirect on single result

  1. Why have the days of “3 clicks” gone? While dynamic content makes it easier for users to perform functions without lots of navigation, they still need to be able to find things. Usability hasn’t gone out of the window surely?

    • I think it is more to do with people’s expectations and the quality and content of websites. The “3 clicks” were born more from techy folks wanting to structure their content logically, rather than focussing on user experience. Such as needlessly adding taxonomies to random content.

      Without the context of widespread bad site design, having to click on a search result when it is the only one will not deter visitors from using the site,

      And also with the prevalence of ajax powered “web 2.0″, people click quite bit without even getting a new page :)

Comments are closed.