Redirect to first post if found only one relevant post in search

hoangvu

New member
Joined
Jun 6, 2012
Messages
1,879
Points
0
Let's start with a snippet that will automatically redirect the reader if you only find a related post while searching. Simply paste the following code in the file functions.php and that was it.

Code:
add_action ('template_redirect', 'redirect_single_post'); 
  function redirect_single_post () { 
      if (is_search ()) { 
          global $ wp_query; 
          if ($ wp_query-> post_count == 1) { 
              wp_redirect (get_permalink ($ wp_query-> posts ['0 '] -> ID)); 
          } 
      } 
  }
 
Older threads
Replies
0
Views
1,487
Replies
5
Views
3,089
Replies
1
Views
4,206
Newer threads
Latest threads
Replies
2
Views
36
Replies
1
Views
19
Replies
0
Views
19
Replies
3
Views
25

Latest postsNew threads

Referral contests

Referral link for :

Sponsors

Latest Blog ArticlesMost Viewed Threads

Popular tags

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

Top