微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php – 显示woocommerce中当前产品的最深的子类别

这看起来应该很容易,但我无法做到,也找不到任何关于它的帖子.

我可以显示与产品或顶级类别相关的所有类别,但您如何仅回显产品的最低/最深类别?

Cat-A [x]
  Cat-B [x]
    Cat-C [x]
  Cat-D [ ]
Cat-E [ ]
  Cat-F [ ]
    Cat-G [ ]
      Cat-H [ ]

如果这个例子是产品的祖先,我想要打印的只是“Cat-C”.

但我不想像其他解决方案那样手动设置类别级别,我希望它始终打印最低的子级,是存档页面上的产品,或单个产品页面.

知道如何做/应该怎么做?

解决方法:

尝试类似的东西:

// get all product cats for the current post
$categories = get_the_terms( get_the_ID(), 'product_cat' ); 

// wrapper to hide any errors from top level categories or products without category
if ( $categories && ! is_wp_error( $category ) ) : 

    // loop through each cat
    foreach($categories as $category) :
      // get the children (if any) of the current cat
      $children = get_categories( array ('taxonomy' => 'product_cat', 'parent' => $category->term_id ));

      if ( count($children) == 0 ) {
          // if no children, then echo the category name.
          echo $category->name;
      }
    endforeach;

endif;

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐