2017-02-15 79 views
1

以下代碼來自wordpress + woocommerce安裝。它應該檢查購物車中的每件物品,如果該物品屬於特定的產品類別(類別ID 79 & 130增加15歐元費用,類別80,136,139增加50歐元費用)相應地向類別添加額外費用。爲簡單起見,我會給他們打電話類別組15€類別組50€PHP的foreach代碼沒有產生效果結果

當一個項目被添加到購物車時,屬於類別組15€或類別組50€,附加費用按預期添加。

當兩個項目添加到購物車時,屬於不同的類別組,附加費用按預期添加。

但是,如果添加到購物車中的多個物品屬於同一類別組,則每個類別組僅添加一個收費項,這是不可取的。添加的每個項目都應產生相關類別組的費用。例如。 2類15歐元組應增加2額外費用,3類50歐元組應增加3額外費用等等。

代碼中是否存在錯誤或...?

function woo_add_cart_fee() { 

global $woocommerce; 

    foreach ($woocommerce->cart->cart_contents as $key => $values) { 
     // Get the terms, i.e. category list using the ID of the product 
    $terms = get_the_terms($values['product_id'], 'product_cat'); 
     // Because a product can have multiple categories, we need to iterate through the list of the products category for a match 
     foreach ($terms as $term) { 
      // 79 is the ID of the category for which we want to remove the payment gateway 
      if($term->term_id == '79' || $term->term_id == '130'){ 
      $excost = 15; 
      $woocommerce->cart->add_fee('Εκτύπωση με απλό μελάνι', $excost, $taxable = false, $tax_class = ''); 
      } else if ($term->term_id == '80' || $term->term_id == '139' || $term->term_id == '136'){ 
       $excost = 50; 
       $woocommerce->cart->add_fee('Μακέτα & εκτύπωση (απλό μελάνι)', $excost, $taxable = false, $tax_class = ''); 
      } 
     } 
    } 
} 

回答

0

您需要使每個費用名稱都是唯一的。

documentation

$名稱 - (字符串)所需的 - 獨特的費用名稱。 無法添加同名的多項費用。

這將是做到這一點的一種方法:

$woocommerce->cart->add_fee('Μακέτα & εκτύπωση (απλό μελάνι) ' . $i++, $excost, $taxable = false, $tax_class = '');