Personality Type: AdLibber

WordPress Function Redirect to Single Post in Category or Taxonomy

A client requested to have a site visitor redirected to the single post if there is only one post in a custom taxonomy.  Thanks to Kevin Chard over at WPSNIPP.COM I found this snippet which redirects user to the post page when the category or tag has only one post (original post).

Add this code to your theme’s functions.php file.

function redirect_to_post(){
    global $wp_query;
    if( is_archive() && $wp_query->post_count == 1 ){
        the_post();
        $post_url = get_permalink();
        wp_redirect( $post_url );
    }
} add_action('template_redirect', 'redirect_to_post');

I was able to then change the query for my custom taxonomy

//Redirect visitor to individual post if only one post for term in Custom Taxonomy
add_filter('pre_get_posts', 'filter_search');

function redirect_to_post(){
    global $wp_query;
    if( ((is_archive())  && get_taxonomy( 'custom_taxonomy')) && $wp_query->post_count == 1 ){
        the_post();
        $post_url = get_permalink();
        wp_redirect( $post_url );
    }
} add_action('template_redirect', 'redirect_to_post');

Works like a dream.