Get category URL by category ID in WooCommerce on product details page

Justin K picture Justin K · Dec 10, 2015 · Viewed 19.6k times · Source

I am looking for category URL on the product detail page. I am using below code to get category ID but I am not sure how to get category URL.

<?php
$terms = get_the_terms( $post->ID, 'product_cat' );
foreach ($terms as $term) {
    echo $product_cat_id = $term->term_id;
    break;
}

Answer

Bas van Stein picture Bas van Stein · Dec 10, 2015

If you have the product category id you can use

$link = get_term_link( $product_cat_id, 'product_cat' );

To get the url of the product category.

edit be sure that the product_cat_id is an integer, use the following line to be completely save:

$link = get_term_link( (int)$product_cat_id, 'product_cat' );