0

I'm a PHP novice putting a site together for a relative. I'm having a hard time with one niggling issue.

I would like to display the product category below the product title and have it link to the product category (it's necessary for this particular product catalog). I would also like this to be a link, which when clicked takes you to that particular product category.

I have found online some source code below which works to a degree - however, it does not link to the product category and I am completely stumped as to how to get it to do so.

Any help would be greatly appreciated.

 add_action( 'woocommerce_after_shop_loop_item_title', 'add_product_cat', 25);
 function add_product_cat() {
 global $product;
 $product_cats = wp_get_post_terms($product->id, 'product_cat');
 $count = count($product_cats);
 foreach($product_cats as $key => $cat)
 {
     echo
    '<span class="category-title">
 <span class= "category-title_'.$cat->slug.'">'.$cat->name.' </span></span>';
   if($key < ($count-1))
     {
         echo ' ';
     }
     else
     {
         echo ' ';
     }
 }
}

closed as off-topic by fuxia Feb 3 '17 at 19:17

This question appears to be off-topic. The users who voted to close gave this specific reason:

If this question can be reworded to fit the rules in the help center, please edit the question.

0

Try this code.

add_action( 'woocommerce_after_shop_loop_item_title', 'add_product_cat', 25);
 function add_product_cat() {
 global $product;
 $product_cats = wp_get_post_terms($product->id, 'product_cat');
 $count = count($product_cats);
 foreach($product_cats as $key => $cat)
 {
     echo
    '<span class="category-title">
        <a href="'. get_term_link( $cat->term_id ) .'"><span class= "category-title_'.$cat->slug.'">'.$cat->name.' </span></a>
        </span>';
   if($key < ($count-1))
     {
         echo ' ';
     }
     else
     {
         echo ' ';
     }
 }
}

Updated Part

<a href="'. get_term_link( $cat->ID ) .'"><span class= "category-title_'.$cat->slug.'">'.$cat->name.' </span></a>

added link to that particular term.

  • Thank you for replying Abdul. I tried something similar to that earlier and it didn't work. I've tried porting your code in however I am met with an error: Catchable fatal error: Object of class WP_Error could not be converted to string. It points to the line containing: <a href="'. get_term_link( $cat->ID ) .'"><span class= "category-title_'.$cat->slug.'">'.$cat->name.' </span></a> – bananapudding Feb 3 '17 at 19:18
  • answer is updated. try with "term_id" instead of just "ID" in get_term_link. – Anwer AR Feb 3 '17 at 19:22
  • awesome. it works. thank you so much for helping me. You've really got me out of a jam! THANKS! – bananapudding Feb 3 '17 at 21:05

Not the answer you're looking for? Browse other questions tagged or ask your own question.