简体   繁体   English

回到 Woocommerce 产品页面中的产品类别

[英]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.此外,即使我删除了这个 If 条件,我也没有得到任何链接。

Thanks!谢谢!

The function get_the_category() is made for WordPress categories, but not for WooCommerce product categories, which is a custom taxonomy.函数get_the_category()是为 WordPress 类别制作的,但不适用于 WooCommerce 产品类别,这是一个自定义分类法。 Same thing for get_category_link() 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.因此,您应该使用带有附加可选参数的wp_get_post_terms()代替,该参数将允许您仅获取父产品类别。 For the link you will use get_term_link() instead:对于链接,您将使用get_term_link()代替:

// 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).代码位于活动子主题(活动主题)的 function.php 文件中。

Tested and works.测试和工作。

Looks like your break statement is breaking the loop even when no condition is met so foreach is terminating even before we have our match.看起来即使没有满足任何条件,您的 break 语句也会中断循环,因此 foreach 甚至在我们匹配之前就终止了。 Try moving the break;尝试移动休息; statement into the if condition block like following:语句进入 if 条件块,如下所示:

     $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; // this will stop the loop as soon as we have a match.
         }

     }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM