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

Marc0

Well-known member
Registered
Joined
Jun 6, 2012
Messages
890
Points
28
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
2,048
Replies
1
Views
2,326
Replies
1
Views
3,995
Replies
11
Views
4,232
Newer Threads
Recommended Threads
Replies
5
Views
1,292
Replies
4
Views
3,182
Replies
18
Views
10,680
Similar Threads

Latest Hosting OffersNew Reviews

Sponsors

Tag Cloud

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