Australia's Leading Digital Marketing Experts. T. 1300 235 433  |  Aggregation Enquires Welcome

Redirect WordPress Search If It Only Returns One Result

Redirect WordPress Search If It Only Returns One Result

If you searched this website for "Jennifer L.awrence" (prior to this post), the search would have redirected you to the only page on this site that contains that text ("Determine A Person's Age From DOB"). It's a fairly specific search term and, given that there's only one result, it's pretty clear what the user is looking for. In such instances, what's the point of generating a "list" of search results? The following code will detect a single search result and redirect the user to the only post or page that matched your search criteria. It's arguably a better user experience and likely to convert a little better than the alternative.

WordPress Code

Copy and paste the WordPress function into your theme's functions.php file or, if you sensibly have one installed, your custom functions plugin.

1
<?php 
2
/*
3
 Redirect WordPress Search To A Post If It Only Returns One Post
4
 http://www.beliefmedia.com/redirect-wordpress-search
5
*/
6
 
7
8
  if (is_search()) {
9
    global $wp_query;
10
    if ($wp_query->post_count == 1) {
11
      wp_redirect( get_permalink( $wp_query->posts['0']->ID ) );
12
    }
13
  }
14
}
15
add_action('template_redirect', 'beliefmedia_single_search');

You can download the code as a function for your custom functions file (labeled as shortcode) or as a plugin below.

Download


Title: Redirect WordPress Searches To a Single Post
Description: The function will redirect a WordPress search result to a post or page if one one result is returned.
  Download • Version 0.2, 718.0B, zip, Category: WordPress Shortcodes
WordPress Plugins (General), (769.0B)    

Download our 650-page guide on Finance Marketing. We'll show you exactly how we generate Billions in volume for our clients.

  AUS Eastern Standard Time (Virginia)

  Want to have a chat?
 

Like this article?

Share on facebook
Share on Facebook
Share on twitter
Share on Twitter
Share on linkedin
Share on Linkdin
Share on pinterest
Share on Pinterest

Leave a comment