2017-08-28 79 views
1

我正在使用woocommerce和額外產品選項插件創建一個非常特殊的電子商店類型,並且我正面臨產品重量的問題。我想修改購物車內的每個產品的重量,具體取決於所選屬性,但沒有運氣。我正在使用這個來改變重量而沒有任何成功。更改每個購物車物品的重量以更新WooCommerce的運費

add_action('woocommerce_before_calculate_totals', 'add_custom_weight', 10, 1); 
function add_custom_weight(WC_Cart $cart) { 
    if (sizeof($cart->cart_contents) > 0) { 
     foreach ($cart->cart_contents as $cart_item_key => $values) { 
      $_product = $values['data']; 

      //very simplified example - every item in cart will be 100 kg 
      $values['data']->weight = '100'; 
     } 
    } 
    var_dump($cart->cart_contents_weight); 
} 

的var_dump返回車的重量,不變(如果我改變之前爲0.5,它將保持0.5),當然還有運費(基於重量)保持不變。有任何想法嗎?

回答

2

由於WooCommerce 3+,你將需要使用上WC_Product對象WC_Product方法。這裏是功能性的方式做到這一點:

add_action('woocommerce_before_calculate_totals', 'add_custom_weight', 10, 1); 
function add_custom_weight($cart_object) { 

    if ((is_admin() && ! defined('DOING_AJAX')) || $cart_object->is_empty()) 
     return; 

    foreach ($cart_object->get_cart() as $cart_item) { 
     //very simplified example - every item in cart will be 100 kg 
     $cart_item['data']->set_weight(100); 
    } 
    // Testing: cart weight output 
    echo '<pre>Cart weight: '; print_r($cart_object->get_cart_contents_weight()); echo '</pre><br>'; 
} 

此代碼放在你的活躍兒童主題(或主題)的function.php文件或也以任何插件文件。

此代碼已經過測試並可正常工作。

相關問題