在 woocommerce_before_calculate_totals 挂钩中获取购物车小计

Get cart subtotal in woocommerce_before_calculate_totals hook

我想在 woocommerce_before_calculate_totals 挂钩中获取 woocommerce 中的购物车总内容。所以为了实现这个我正在使用这个代码

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
}

但是每次都是returns0。那么有人可以告诉我如何在 woocommerce_before_calculate_totals 挂钩内获得没有货币的购物车总数吗?

任何帮助和建议都将不胜感激。

/* 改变这一行 WC()->购物车->get_cart_contents_total() 和 $woocommerce->购物车->get_cart_total() 因为你定义了 global $woocommerce;对于 woocommerce 对象 */

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

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
}