WordPress Snippets at WPcustoms

Auto redirect to post if category\tag is 1

If a category or tag page contains only one post this function automatically forwards your visitor to that post.


/**
 * Snippet Name: Auto redirect to post if category\tag is 1
 * Snippet URL: http://www.wpcustoms.net/snippets/auto-redirect-post-categorytag-1/
 */
 function wpc_redirect_to_post(){
    global $wp_query;
  
    // If there is one post on archive page
    if( is_archive() && $wp_query->post_count == 1 ){
        // Setup post data
        the_post();
        // Get permalink
        $post_url = get_permalink();
        // Redirect to post page
        wp_redirect( $post_url );
    }  
  
} 
add_action('template_redirect', 'wpc_redirect_to_post');