2016-11-24 86 views
3

我的代碼運行良好,但僅適用於一隻貓(此處爲ID 25)。
難以添加第二個類別(ID 24)。
根據2個產品類別收取額外費用

這我使用的類ID 25碼:

function df_add_ticket_surcharge($cart_object) { 

    global $woocommerce; 
    $specialfeecat = 25; // category id for the special fee 
    $spfee = 2; // initialize special fee 
    $spfeeperprod = 0.0; //special fee per product 

    foreach ($cart_object->cart_contents as $key => $value) { 

     $proid = $value['product_id']; //get the product id from cart 
     $quantiy = $value['quantity']; //get quantity from cart 
     $itmprice = $value['data']->price; //get product price 

     $terms = get_the_terms($proid, 'product_cat'); //get taxonamy of the prducts 
     if ($terms && ! is_wp_error($terms)) : 
      foreach ($terms as $term) { 
       $catid = $term->term_id; 
       if($specialfeecat == $catid) { 
        $spfee = $spfee + $itmprice * $quantiy * $spfeeperprod; 
       } 
      } 
     endif; 
    } 

    if($spfee > 0) { 

     $woocommerce->cart->add_fee('Supp. préparation fruit légumes', $spfee, true, 'standard'); 
    } 
} 
add_action('woocommerce_cart_calculate_fees', 'df_add_ticket_surcharge'); 

我該怎麼做才能處理2個類別在此代碼?

感謝

回答

0

使用相關產品類別的條件,最短,最快捷和有效的方式是使用has_term()與「product_cat」分類WordPress的功能...

所以,你的代碼將是這樣的:

add_action('woocommerce_cart_calculate_fees', 'df_add_ticket_surcharge', 10, 1); 
function df_add_ticket_surcharge() { 

    if (is_admin() && ! defined('DOING_AJAX')) 
     return; 

    $specialfeecat = 25; // category id for the special fee 
    $spfee = 2; // initialize special fee 
    $spfeeperprod = 0.05; //special fee per product (5% here) 

    foreach (WC()->cart_contents as $cart_item) { 

     $item_id = $cart_item['product_id']; //get the product id from cart 
     $item_qty = $cart_item['quantity']; //get quantity from cart 
     $item_price = $cart_item['data']->price; //get product price 

     if(has_term(24, 'product_cat', $item_id) || has_term(25, 'product_cat', $item_id)) { 
      $spfee = $spfee + $item_price * $item_qty * $spfeeperprod; 
      // you may need "break;" if you have multiple items in cart (to stop the calculation) 
      // because $spfee is going to grow with each additional item 
      break; 
     } 
    } 

    if($spfee > 0) 
     WC()->cart->add_fee('Supp. préparation fruit légumes', $spfee, true, 'standard'); 

} 

我有一個值也添加到您的$spfeeperprod變量,如果你一直0.0您將永遠得到一個0費用值計算。

也要照顧大約在foreach循環中的$ spfee計算,因爲如果有一個以上的對應項目,計算將是在每個循環增加...

相關參考資料:

相關問題