在 woocommerce_before_calculate_totals 钩子中获取购物车小计 [英] Get cart subtotal in woocommerce_before_calculate_totals hook

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

问题描述

我想在 woocommerce_before_calculate_totals 钩子内获取 woocommerce 中的购物车内容总数.所以为了实现这一点,我使用了这段代码

I want to get cart contents total in woocommerce within woocommerce_before_calculate_totals hook. So to achieve this I am using this code

add_action( 'woocommerce_before_calculate_totals', 'get_before_calculate_totals', 10 );
function get_before_calculate_totals( $cart_object ) {
    global $woocommerce;
    echo WC()->cart->get_cart_contents_total(); //returns 0
}

但是每次都返回0.那么有人能告诉我如何在 woocommerce_before_calculate_totals 钩子内获得没有货币的购物车总数吗?

But it returns 0 every time. So can someone tell me how to get cart total without currency within woocommerce_before_calculate_totals hook?

任何帮助和建议都会非常值得赞赏.

Any help and suggestion would be really appreciable.

推荐答案

由于 woocommerce_before_calculate_totals 在任何总计计算之前使用,请改用以下进行项目小计计算的内容:

As woocommerce_before_calculate_totals is used before any totals calculations, use instead the following that makes items subtotals calculations:

add_action( 'woocommerce_before_calculate_totals', 'get_subtotal_before_calculate_totals', 10 );
function get_subtotal_before_calculate_totals( $cart ) {
    $subtotal_excl_tax = $subtotal_incl_tax = 0; // Initializing

    // Loop though cart items
    foreach( $cart->get_cart() as $cart_item ) {
        $subtotal_excl_tax += $cart_item['line_subtotal'];
        $subtotal_incl_tax += $cart_item['line_subtotal'] + $cart_item['line_subtotal_tax'];
    }
    echo '<p>Subtotal excl. tax: ' . $subtotal_excl_tax . '</p>'; // Testing output
    echo '<p>Subtotal Incl. tax: ' . $subtotal_incl_tax . '</p>'; // Testing output
}

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

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