显示woocommerce中当前产品的最深子类别 [英] Display deepest child category for current product in woocommerce

查看:74
本文介绍了显示woocommerce中当前产品的最深子类别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

This seems like it should be easy to do but I haven't been able to, and cannot find any posts regarding it.

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

I can display all the categories associated with a product, or the top category, but how do you echo only the lowest / deepest category for a product?

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

如果此示例是产品的血统,我想打印的只是 Cat-C。

If this example is the product's ancestry, all I want to print is "Cat-C".

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

But I don't want to manually set the category level like other solutions, I want it to always print the lowest child, be the product on the archive page, or single product page.

关于如何/应该这样做的任何想法?

Any idea of how this can / should be done?

推荐答案

尝试类似的操作:

// 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;

这篇关于显示woocommerce中当前产品的最深子类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆