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

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


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' );


You can use get_category_link(int|object $category)

https://developer.wordpress.org/reference/functions/get_category_link/

And here how I use it on 'content-product_cat.php'

<a href="<?php esc_url_e( get_category_link( $category->term_id ) ); ?>">        <h5 class="product-name"><?php esc_attr_e( $category->name ); ?></h5>        <span class="dima-divider line-center line-hr small-line"></span>        <span class="count">        <?php  if ( $category->count > 0 ) {        echo apply_filters( 'woocommerce_subcategory_count_html', $category->count . ' ' . ( $category->count > 1 ? __( 'Products', 'woocommerce' ) : __( 'Product', 'woocommerce' ) ), $category );        }?>        </span></a>


If a product belongs to one or many category then you can directly access the $terms[0] location and retrieve the URL

Here is the code:

global $post;$link = '';$terms = get_the_terms( $post->ID, 'product_cat' );if(!empty($terms[0])){    $link = get_term_link( $terms[0]->term_id, 'product_cat' );}

Now just check $link is empty or not and do your required stuff.

Code is tested and works.

Hope this helps!