WordPress - redirect to the post instead of archive page when search query returns single result


/ Published in: PHP
Save to your folder(s)

Courtesy Kevin Chard at WPSnipp.com.

Adding this snippet to the functions.php of your wordpress theme will redirect your search to the post automatically when wordpress only returns a single search result.


Copy this code and paste it in your HTML
  1. add_action('template_redirect', 'single_result');
  2. function single_result() {
  3. if (is_search()) {
  4. global $wp_query;
  5. if ($wp_query->post_count == 1) {
  6. wp_redirect( get_permalink( $wp_query->posts['0']->ID ) );
  7. }
  8. }
  9. }

URL: http://wpsnipp.com/index.php/functions-php/redirect-to-post-when-search-query-returns-single-result/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.