Skip to content

Instantly share code, notes, and snippets.

@dartiss
Created November 15, 2017 16:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dartiss/62668640c06a8c3cf9aeb0a1666fccf3 to your computer and use it in GitHub Desktop.
Save dartiss/62668640c06a8c3cf9aeb0a1666fccf3 to your computer and use it in GitHub Desktop.
Show Post if Search Returns One Result
<?php
function single_result() {
if ( is_search() ) {
global $wp_query;
if ( $wp_query -> post_count == 1 && $wp_query -> max_num_pages == 1 ) {
wp_redirect( get_permalink( $wp_query -> posts[ 0 ] -> ID ) );
exit;
}
}
}
add_action( 'template_redirect', 'single_result' );
?>
@dartiss
Copy link
Author

dartiss commented Nov 15, 2017

Few things in life (okay, I exaggerate) are more annoying than searching for something, getting one result and you still have to click it to view it - this rectifies that. Simply add to your theme's functions.php.

Thanks to my fellow Automattician Kailey [for the original code](https://trepmal.com/2011/04/22/redirect-when-search-query-only-returns-one-match/).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment