Change cart items weight to update the shipping co

2020-03-31 04:34发布

问题:

I am creating a very particular type of e-shop using Woocommerce and Extra Product Options plugin and I am facing a problem with the weights of the products.

I want to modify the weight of each product inside the cart, depending on the selected attribute, without luck. I am using this to alter the weight without any success.

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 the weight of the cart, unaltered (if it was 0.5 before my change, it will remain 0.5) and of course shipping costs (based on the weight) remain unaltered. Any ideas?

回答1:

Updated (may 2019)

Since WooCommerce 3+, you will need to use WC_Product methods on WC_Product objects. Here is the functional way to do it:

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)
}

Code goes in functions.php file of your active child theme (or active theme). Tested and works.