WooCommerce - 在订单电子邮件中显示来自特定类别父级的子类别

WooCommerce - Display sub-category from specific category parent in order email

所以我有一个关于在 WooCommerce 中确认订单后发送的订单电子邮件中显示产品分配给哪些子类别的奇怪请求 - 但是我只想显示来自特定类别父级的类别。

你看,我在 WooCommerce 中有两个主要类别,一个是品牌,另一个是类别。我只想显示分配给品牌类别下特定产品的子类别。在我的例子中,品牌类别(父级)的 ID 为 15。

我目前测试并确认有效的代码片段是这个

function modfuel_woocommerce_before_order_add_cat($name, $item){

   $product_id = $item['product_id'];

   $_product = wc_get_product( $product_id );
   $htmlStr = "";
   $cats = "";
   $terms = get_the_terms( $product_id, 'product_cat' );

   $count = 0;
   foreach ( $terms as $term) {
    $count++;

    if($count > 1){
      $cats .= $term->name;
    }
    else{
      $cats .= $term->name . ',';
    }

   }

   $cats = rtrim($cats,',');

   $htmlStr .= $_product->get_title();

   $htmlStr .= "<p>Category: " . $cats . "</p>";

   return $htmlStr;
}

add_filter('woocommerce_order_item_name','modfuel_woocommerce_before_order_add_cat', 10, 2);

这里有人知道我可以在上面的代码中添加什么以获得我需要的东西吗?

谢谢!

如果我理解你的代码,你现在拥有 $terms 中的所有类别并且想要跳过所有不是品牌子项的术语。

您可以直接跳过没有此父项的条款。你的代码看起来像这样:

function modfuel_woocommerce_before_order_add_cat($name, $item){

   $product_id = $item['product_id'];

   $_product = wc_get_product( $product_id );
   $htmlStr = "";
   $cats = "";
   $terms = get_the_terms( $product_id, 'product_cat' );

   $count = 0;
   foreach ( $terms as $term) {
    if ($term->parent != 15) continue;
    $count++;

    if($count > 1){
      $cats .= $term->name;
    }
    else{
      $cats .= $term->name . ',';
    }

   }

   $cats = rtrim($cats,',');

   $htmlStr .= $_product->get_title();

   $htmlStr .= "<p>Category: " . $cats . "</p>";

   return $htmlStr;
}

add_filter('woocommerce_order_item_name','modfuel_woocommerce_before_order_add_cat', 10, 2);

我添加了 if ($term->parent != 15) continue; 代码以跳过该术语,如果它不是 Brand(ID:15)的直接子项。