I found this code on an old overflow post that helped me get back to the main product category after opening a certain product:
add_action ('woocommerce_before_single_product','add_back_product_category_button', 5);
function add_back_product_category_button(){
// Get the product categories set in the product
$terms = wp_get_post_terms( get_the_id(), 'product_cat' );
// Check that there is at leat one product category set for the product
if(sizeof($terms) > 0){
// Get the first product category WP_Term object
$term = reset($terms);
// Get the term link (button link)
$link = get_term_link( $term, 'product_cat' );
// Button text
$text = __('Voltar a','woocommerce') . ' <strong>' . $term->name . '</strong>';
// Output
echo '<p><a href="'.esc_url($link).'" title="'.$text.'" class="button '.$term->slug.'">'.$text.'</a></p>';
}
}
Although this code is very useful, I felt the need to make my customers be able to return to the subcategory before returning to the main category.
Per example:
When my customer visits the category "Woman" and then the subcategory "Skirts", they can go back to "Woman" with no problem. The problem urges when my customer visits a certain product inside "Skits". In the product page, if they click on the code created back button, they go to "Woman", and not to "Skirts".
So, is the customer is at: Woman -> Skirts -> Product they should go back to Skirts, not to Woman when they click on the code created back button.
I hope this was clear enough!
Cheers