WordPress Snippets at WPcustoms

Auto redirect to post if search result is 1

if the search returns only 1 post it will automatically forward your visitor to that returned post.


/**
 * Snippet Name: Auto redirect to post if search result is 1
 * Snippet URL: https://wpcustoms.net/snippets/auto-redirect-to-post-if-search-result-is-1/
 */
  function wpc_redirect_single_post() {
    if (is_search()) {
        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', 'wpc_redirect_single_post');