在WooCommerce中更新购物车小计 [英] Updating cart subtotal in WooCommerce

查看:94
本文介绍了在WooCommerce中更新购物车小计的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to update cart subtotal in WooCommerce.

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

How can add action for modifying subtotal in WooCommerce?

我已尝试通过此代码进行操作,但无法正常工作。我想将购物车小计12乘以并在购物车页面上显示此计算。

I have tried to by this code, but is not working. I would like to multiply by 12 the cart subtotal and to display this calculation on cart page.

这是我的代码:

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


推荐答案

您使用正确的钩子,这是Woocommerce版本2.6x到3.0+的功能和经过测试的代码,这将解决问题(相反,您可以对购物车中的商品进行计算,您将得到相同的结果)

You are using the right hook and here is the functional and tested code for Woocommerce version 2.6x to 3.0+, that is going to do the trick (instead you can make your calculation on cart items, and you will get the same thing) :

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文件中,或者在任何插件文件中。


说明:

使用基于购物车小计的计算,将仅在购物车小计行上显示计算,而不会更新购物车商品,购物车商品行小计以及购物车总计。

Using a calculation based on the cart subtotal, will only display the calculation on subtotal cart line row, without updating the cart items, the cart items line subtotals, and the cart total.

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

You can see it trying this working code for WooCommerce version 2.6.x and 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文件中,或者

这篇关于在WooCommerce中更新购物车小计的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆