Wordpress Snippets

Redirect User To Post If Search Results Return One Post

Recently on a project, my client asked me to develop a system to redirect user to post if search results returns only one post. Although it’s fairly simple system to develop but I started searching on Google if someone has already tried to develop similar function. Fortunately WordPress developer Paul Underwood has shared a WordPress code snippet for this on his website. All I had to do is to use his snippet and modify it further for my client’s requirements. I also thought it would be nice to share it with you guys since it’s really nice feature to have on your website to redirect user to post directly if search results only return one post. You may also like to add search form in your post content by using shortcode.

Paul used template_redirect WordPress action in his WordPress snippet to check if the user is searching and if there is only one search result is returned then redirect user to the post directly instead of showing search results. So here is the function, which you can simply paste in your theme’s functions.php file. You don’t need to modify anything in this code snippet as it will work out of the box and redirect user to post if only one search result available.

// redirect user to post if search results return one post
function redirect_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_single_post' );

source

Hire Us. Or just say Hi!
Need a job? Apply to get one.