【问题标题】:Updating cart subtotal in WooCommerce在 WooCommerce 中更新购物车小计
【发布时间】:2017-05-11 12:16:23
【问题描述】:

我想在 WooCommerce 中更新购物车小计。

如何在 WooCommerce 中添加修改小计的操作?

我已尝试使用此代码,但无法正常工作。我想将购物车小计乘以 12 并将此计算结果显示在购物车页面上。

这是我的代码:

add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' );
function add_custom_price( $total) {

    foreach ( $total->cart_contents as $key => $value ) {

        $modifiedtotal = $total->subtotal * 12; 
        // --------------------------------
        //how can get subtotal with multiply by 12 and it should be show on cart page.
    }
}

【问题讨论】:

    标签: php wordpress woocommerce cart hook-woocommerce


    【解决方案1】:

    您使用了正确的钩子,这里是 Woocommerce 版本 2.6x 到 3.0+ 的功能和测试代码,这将起到作用(相反,您可以对购物车项目进行计算,您将得到同样的东西)

    add_action( 'woocommerce_before_calculate_totals', 'add_custom_price', 10, 1);
    function add_custom_price( $cart_object ) {
    
        if ( is_admin() && ! defined( 'DOING_AJAX' ) )
            return;
    
        if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
            return;
    
        foreach ( $cart_object->get_cart() as $cart_item ) {
            ## Price calculation ##
            $price = $cart_item['data']->price * 12;
    
            ## Set the price with WooCommerce compatibility ##
            if ( version_compare( WC_VERSION, '3.0', '<' ) ) {
                $cart_item['data']->price = $price; // Before WC 3.0
            } else {
                $cart_item['data']->set_price( $price ); // WC 3.0+
            }
        }
    }
    

    代码进入您的活动子主题(或主题)的 function.php 文件或任何插件文件中。


    说明:

    使用基于购物车小计的计算,将只显示小计购物车行的计算,不会更新购物车商品、购物车商品行小计和购物车总计。

    您可以看到它正在为 WooCommerce 版本 2.6.x 和 3.0+ 尝试此工作代码:

    add_action( 'woocommerce_calculate_totals', 'add_custom_price', 10, 1);
    function add_custom_price( $cart_object ) {
    
        if ( is_admin() && ! defined( 'DOING_AJAX' ) )
            return;
    
        if ( did_action( 'woocommerce_calculate_totals' ) >= 2 )
            return;
    
        $cart_object->subtotal *= 12;
    }
    

    代码进入您的活动子主题(或主题)的 function.php 文件或任何插件文件中。

    【讨论】:

    • 嘿.....非常感谢,非常感谢。它对我有用。是的,这是版本问题。再次感谢。
    • 只有一个查询。我想用小计标签显示相乘的总金额。实际上这个代码显示乘以单价,用户可能会混淆产品单价。你能在小计中只显示乘法量吗?提前致谢。
    • 您刚刚救了一条命,大人。
    【解决方案2】:

    使用'woocommerce_calculate_totals' 而不是'woocommerce_before_calculate_totals'

    【讨论】:

    • 感谢您的回复。我已经检查过了,但没有成功。你能把代码放在这里,我可以用乘以 12 显示小计。
    猜你喜欢
    • 1970-01-01
    • 2018-07-29
    • 1970-01-01
    • 2015-02-03
    • 1970-01-01
    • 2021-08-21
    • 2016-10-06
    • 2015-05-11
    • 2019-08-07
    相关资源
    最近更新 更多