Redirect To Post If Search Results Return One Post

  • follow us in feedly
Published March 9, 2013 by Brad Knutson
WordPress Redirect Search Results

A lot of WordPress sites utilize the built in search functionality to allow users to find posts relevant to what they are interested in. WordPress’ search functionality is actually really easy to work with and it produces excellent results very quickly.

I’ve written before about making the search results even better, by highlighting search results, but what about search queries that only generate one result? Wouldn’t it make more sense just to redirect the user to that page, as opposed to a search page with only one result?

Like most other problems WordPress developers face, there is an easy solution. We’ll utilize the wp_redirect built-in function.

Add the below function into your theme’s functions.php file.

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

Essentially what this function does is:

  1. Checks if the page requested is a search results page.
  2. Then checks if the query returns only one result.
  3. Then calls the wp_redirect function to send the user to the permalink for the one search result.

Pretty simple right?

The following two tabs change content below.
Founder at Inbounderish
Brad Knutson is a Web Developer in the Twin Cities area of Minnesota. He has experience working with WordPress and Drupal, and also has an interest in SEO and Inbound Marketing.

Keep Up-to-Date



See a complete list of topics discussed in blog posts here.

Check These Out

Get 2 Weeks Free! Sign Up Today! Premium Managed WordPress Hosting Genesis Framework for WordPress SEO is complex. Tools should be simple. Thesis Theme for WordPress:  Options Galore and a Helpful Support Community

Share Your Thoughts

Your email address will not be shown.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">