Skip to content
Advertisement

Set back to product category in Woocommerce Product Page

I want to set a back button on my product page (to the product category). I cant manage to get the category and echo on the page.

I have tried to use this code and it doesn’t work…

         $cats=get_the_category();
         foreach($cats as $cat){

             if($cat->category_parent == 0 && $cat->term_id != 1){
                 echo '<h2 class="link"><a href="'.get_category_link($cat->term_id ).'">Return</a></h2>';
             }
             break;
         }

The first problem I have whit this code is what I have no option to set the parent category for the product. (If you can help me how can is set it, it will be great).

Also even if I’m removing this If condition, I don’t get any link.

Thanks!

Advertisement

Answer

The function get_the_category() is made for WordPress categories, but not for WooCommerce product categories, which is a custom taxonomy. Same thing for get_category_link()

So you should use instead wp_get_post_terms() with an additional optional argument that will allow you to get only parent product categories. For the link you will use get_term_link() instead:

// Get parent product categories on single product pages
$terms = wp_get_post_terms( get_the_id(), 'product_cat', array( 'include_children' => false ) );

// Get the first main product category (not a child one)
$term = reset($terms);
$term_link =  get_term_link( $term->term_id, 'product_cat' ); // The link
echo '<h2 class="link"><a href="'.$term_link.'">Return</a></h2>';

Code goes in function.php file of your active child theme (active theme).

Tested and works.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement