Search code examples
phpwordpresswoocommercecategorieswoocommerce-theming

Woocommerce how to make the category linkable


I have an issue where I want to show my item category for a store item AND make it clickable.

As I'm a total novice in php (basically illiterate) and have no acquaintances who could help me with it, I turn to you.

add_action( 'woocommerce_after_shop_loop_item_title', 'puhe_show_all_subcats', 2 );
 
function puhe_show_all_subcats() {
   global $product;
   $cats = get_the_terms( $product->get_id(), 'product_cat' );
   if ( empty( $cats ) ) return;
   echo join( ', ', wp_list_pluck( $cats, 'name' ) );
}

And I got a hind that I should be using the following somewhere in there

echo '<a href="' . site_url() . '/product-category/' . $term->slug . '">' . $term->name . '</a>';

But as much (or little) as I know from programming I still have to define $term somewhere (?).

But can somewhat help me make these two work together so that it would fetch the proper category (that the first part basically does) and it would fetch the location for it and make it a link.


Solution

  • Its best to leverage the inbuilt WooCommerce function for this purpose. Try using the following code:

    echo wc_get_product_category_list( $product->get_id());
    

    Reference: function_wc_get_product_category_list()