Want to redirect to post if search results only returns one post in WordPress? Use following code in your theme’s functions.php file OR in site specific plugin.
1 2 3 4 5 6 7 8 9 10 |
function redirect_the_single_post() { if (is_search() && is_main_query()) { 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', 'redirect_the_single_post' ); |
Hope this will help you!
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.