I think you can simply use WP_Term
‘s $count
property which should hold the number of posts attached to this current term.
Then, if only one post is attached to this term, query this post object and do your stuff with it…
$term = get_queried_object();
if ( $term->count === 1 ) {
$args = array(
'tax_query' => array(
array(
'taxonomy' => 'product_range',
'field' => 'term_id',
'terms' => array( $term->term_id ),
'include_children' => false,
),
)
);
$query = new WP_Query( $args );
$posts = $query->posts;
$post = $posts[0];
/**
* IMPORTANT FOR SEO...
* Temporary redirection until your category is populated - Use 301 instead of 302 to redirect permanently...
*/
if ( wp_redirect( get_permalink( $post->ID ), 302 ) ) {
exit;
}
}