If Search Results Returns One Post, Redirect To Post

By default WordPress comes with search functionality. This is great because if your visitors can not find the post(s) they are looking for, they can quickly search for it.When a visitor performs a search, WordPress will display the results using the theme’s search.php file. This page can be customized to your liking.

The problem is the search page will show all posts that match your search query, even if it’s a single post.

Instead of displaying a single result on the search page, you can redirect the visitor to that page. Here is the code snippet to do just that:

function redirect_single_post_search() { 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_single_post_search' );

Add the above code snippet to your theme’s functions.php file.

You’re done! If the search results returns one post, the visitor will be redirect to that post.