【问题标题】:Change cart items weight to update the shipping costs in Woocommerce更改购物车商品重量以更新 Woocommerce 中的运费
【发布时间】:2018-02-05 11:03:43
【问题描述】:

我正在使用 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 返回购物车的重量,不变(如果在我更改之前它是 0.5,它将保持 0.5),当然运输成本(基于重量)保持不变。有什么想法吗?

【问题讨论】:

    标签: php wordpress woocommerce properties cart


    【解决方案1】:

    更新 (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 文件中。经过测试并且可以工作。

    【讨论】:

    • 这似乎确实有效,并增加了购物车中产品的重量,但是当我试图确定运费时,我在结账时有一个不断旋转的图标,这是否与后者不兼容Woocommerce 的版本? (我正在运行 3.6.2)
    • @jfar_magnetik 你能清理一下吗(请移除所有 cmets)……你可以尝试使用更高的钩子优先级,例如将10(实际优先级)替换为1000。跨度>
    猜你喜欢
    • 2018-01-30
    • 2014-07-25
    • 2018-07-31
    • 1970-01-01
    • 1970-01-01
    • 2019-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多