首页 > 解决方案 > 在 woocommerce_before_calculate_totals 挂钩中获取购物车小计

问题描述

我想在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
}

但它每次都返回 0。那么有人可以告诉我如何在没有货币的情况下获得购物车总数woocommerce_before_calculate_totals吗?

任何帮助和建议都将是非常可观的。

标签: phpwordpresswoocommercecarthook-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
}

推荐阅读