Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
}
like image 930
Justin K Avatar asked Dec 10 '15 15:12

Justin K


3 Answers

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' );
like image 130
Bas van Stein Avatar answered Oct 26 '22 14:10

Bas van Stein


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>
like image 45
Adel Avatar answered Oct 26 '22 15:10

Adel


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!

like image 23
Raunak Gupta Avatar answered Oct 26 '22 13:10

Raunak Gupta