Change cart items weight to update the shipping costs in Woocommerce

与世无争的帅哥 提交于 2019-11-29 16:21:19

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.

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