Change link in get_terms if there is only one post in the category

I created a shortcode that will list the categories in my custom taxonomy and will return a list of all the categories that have at least 1 post (not empty).

The result is that when someone clicks on my links it takes them to an archive page of that category.

My question is if it’s possible that when there is only one post in that category, that i can send the user directly to the post instead of to the archive wiht only a single post on it?

this is my code:

// Creates a list of eval specialties
function doc_categories() {
$tax = 'team_group';  // slug of taxonomy to list

$terms = get_terms($tax, array('hide_empty' => 1 ));
$specials="<div>";
foreach ($terms as $term) {
        $slug = $term->slug;
        $description = $term->description;
        $link = "<a href="https://wordpress.stackexchange.com/?$tax=$slug" ><h5> $term->name </h5></a>";
        $imglink ="<a href="https://wordpress.stackexchange.com/?$tax=$slug" ><img src="".z_taxonomy_image_url($term->term_id).""></a>";

$specials .='<div class="flex_column av_one_third specialty flex_column_div">';
$specials .='<div class="specialty-name"'.$link.'</div>';
$specials .= $imglink;
$specials .= '</div>';
        }
$specials .= '</div>';
return $specials;
}
add_shortcode( 'evalspecialties', 'doc_categories' );

2 Answers
2

This could be done in the template that displays your archive page when only one post is returned by wp_query for a given category. Something like this:

if ( $wp_query->post_count == 1 && $wp_query->max_num_pages == 1 ) {
    wp_redirect( get_permalink( $wp_query->posts['0']->ID ) );
    exit;
}

Leave a Comment