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条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度