WordPress category archives when the category only has one post

A client site uses custom post type taxonomies to set up a few distinct sections. The category archive page typically lists all post titles with a link, but there was one category that had just one post. In that instance, it would be nice to save the viewer a click and show the post directly.

A quick way to do handle this is to check if a category has multiple posts. This bit of code goes in the category template and says if there is only one post, show the content (in this case a custom field called member_content), but if there are multiple posts show the title and link:

<?php if ($wp_query->found_posts == 1) : 
            echo get_field('member_content'); 
          else: ?>
            <h4><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h4>
        <?php endif; ?>

But sometimes the category archive page has a different design and simply showing post content there won’t work. A better option would be to redirect to the post. This code goes in the functions.php file:

        function stf_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
        // Get permalink
        $post_url = get_permalink();
        // Redirect to post page
        wp_redirect( $post_url );
} add_action('template_redirect', 'stf_redirect_to_post');

This second bit of code came from here.