Skip to content

Instantly share code, notes, and snippets.

@GaryJones
Forked from miklb/gist:2437076
Created April 21, 2012 13:55
Show Gist options
  • Select an option

  • Save GaryJones/2437195 to your computer and use it in GitHub Desktop.

Select an option

Save GaryJones/2437195 to your computer and use it in GitHub Desktop.
WordPress redirect single search result
<?php
add_action( 'template_redirect', 'kkf_single_search_redirect' );
/**
* If only one search result match, automatically redirect to that result.
*
* @author Michael Bishop
* @link https://gist.github.com/2437076
*
* @global WP_Query $wp_query Query object.
*
* @return null Returns early if not a search query.
*/
function kkf_single_search_redirect() {
if ( ! is_search() )
return;
global $wp_query;
if ( 1 == $wp_query->post_count ) {
wp_redirect( get_permalink( $wp_query->posts['0']->ID ) );
exit;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment