更改每个购物车物品的重量以更新WooCommerce的运费
问题描述:
我正在使用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),当然还有运费(基于重量)保持不变。有任何想法吗?
答
由于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文件或也以任何插件文件。
此代码已经过测试并可正常工作。