duanjiuhong5843 2014-09-17 17:38
浏览 62
已采纳

在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 [ ]

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?

  • 写回答

2条回答 默认 最新

  • doulai2573 2014-09-18 03:12
    关注

    Try something like:

    // 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;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看