-
-
Save GaryJones/2437195 to your computer and use it in GitHub Desktop.
WordPress redirect single search result
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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