Woocommerce – when there in only one product in a category - Designagogo Journal

Musings & minor discoveries

Woocommerce – when there in only one product in a category

The default Woocommerce front page template lists all the product categories in a shop, and then if you click on one of these, you’d see an archive page showing all the relevant products within that category. You’d then click on one of the thumbnails to go into the product details page. This is all pretty standard.

However, this is not always great if some of your categories have only one product in them. In such cases, it’s often better for the category link in the shop front page go directly to the product page (single-product.php), rather than via the category archive (taxonomy-product_category.php) which would show only one product and therefore a waste of a click.

After some searching on Google, this post seemed to contain the answer, but since I had simplified my template structure, it did not work for me. I had a custom loop in archive_product.php which iterated through each product category and then, under each, created a list of subcategories.

In the foreach($subcats as $subcat) statement, which looks through each subcategory, I added the following which basically just redefines the $link variable if only one post is found for a particular subcategory:

//get number of posts for this subcat
echo $num_posts = $subcat->count;
$link = get_term_link($subcat->slug, 'product_cat');
//If there is only one post, get the post details and reset the link to
//that instead of the category link. This is done through another query
if($num_posts == 1){
$query_args = array( 'showposts'=>1,'post_status' => 'publish', 'post_type' => 'product',
'tax_query' => array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $subcat->slug
$single_post = new WP_Query($query_args);
while ($single_post->have_posts()) : $single_post->the_post();
global $product;
$link = get_permalink();