更改购物车商品重量以更新 Woocommerce 中的运费

Change cart items weight to update the shipping costs in Woocommerce

我正在使用 Woocommerce 和 Extra Product Options 插件创建一个非常特殊类型的电子商店,但我遇到了产品重量的问题。

我想根据所选属性修改购物车中每个产品的重量,但运气不好。我正在使用它来改变重量,但没有成功。

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 returns 购物车的重量,未改变(如果在我改变之前是 0.5,它将保持 0.5),当然运费(基于重量)保持不变。有什么想法吗?

已更新 (2019 年 5 月)

从 WooCommerce 3+ 开始,您需要在 WC_Product 对象上使用 WC_Product 方法。这是实现它的功能方法:

add_action( 'woocommerce_before_calculate_totals', 'add_custom_weight', 10, 1 );
function add_custom_weight( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    foreach ( $cart->get_cart() as $cart_item ) {
         //very simplified example - every item in cart will be 100 kg
        $cart_item['data']->set_weight( 100 );
    }
    // print_r( $cart->get_cart_contents_weight() ); // Only for testing (not on checkout page)
}

代码进入您的活动子主题(或活动主题)的 functions.php 文件。已测试并有效。