Change cart items weight to update the shipping costs in Woocommerce

社会主义新天地 提交于 2019-11-28 06:06:41

问题


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.



来源:https://stackoverflow.com/questions/45914552/change-cart-items-weight-to-update-the-shipping-costs-in-woocommerce

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!