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

标签 php wordpress woocommerce categories

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

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

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;

关于php - 在 woocommerce 中显示当前产品的最深子类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25896981/

相关文章:

php - 没有定期刷新的 AJAX 聊天?

php - 在 Woocommerce 中添加基于产品类别的自定义结帐字段

php - WordPress 在内存中存储身份验证 token

php - 正在用 php 发送一个额外的附件

php - PHPDoc 中严格类型实体的提示迭代器

php - Laravel 有很多更新关系

php - Woocommerce 中定义的产品类别中仅允许购物车中的一件商品

php - 将相关产品类别描述附加到 Woocommerce 中的产品描述

WordPress/ACF : Sort Posts by multiple fields

php - 在 Woocommerce 中获取并显示产品类别特色图像