skip to Main Content

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.

2

Answers


  1. You need to use get_term_link to get your category permalink.

    You could read more about it on the documentation page:

    WordPress get_term_link function

    You could set it up in multiple ways, for example, you could do somthing like this:

    global $product;
    
    $cats = get_the_terms( $product->get_id(), 'product_cat' );
    
    foreach ($cats as $cat) {
        echo '<li><a href="'.get_term_link($cat->term_id, 'product_cat').'">'.$cat->name.'</a></li>';
    }
    

    Since you’re using woocommerce then you could use wc_get_product_category_list too!

    <?php echo wc_get_product_category_list( $product->get_id(), ', ', '<span class="posted_in">' . _n( 'Category:', 'Categories:', count( $product->get_category_ids() ), 'woocommerce' ) . ' ', '</span>' ); ?>
    

    AND also This great answer might help you as well!

    Login or Signup to reply.
  2. 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()

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search