【问题标题】:WooCommerce - Display sub-category from specific category parent in order emailWooCommerce - 在订单电子邮件中显示来自特定类别父级的子类别
【发布时间】:2021-01-13 22:30:30
【问题描述】:

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

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

我目前测试并确认可以工作的代码sn-p是这样的

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

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

谢谢!

【问题讨论】:

    标签: php wordpress woocommerce categories


    【解决方案1】:

    如果我正确理解您的代码,您现在拥有 $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);
    

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

    【讨论】:

    • 你我的男人应该得到一个大的数字高五!这正是我所需要的。非常感谢!
    猜你喜欢
    • 2018-06-04
    • 2013-01-24
    • 1970-01-01
    • 1970-01-01
    • 2015-12-16
    • 2018-12-07
    • 2018-09-23
    • 2021-08-16
    • 1970-01-01
    相关资源
    最近更新 更多