【问题标题】:Get cart subtotal in woocommerce_before_calculate_totals hook在 woocommerce_before_calculate_totals 挂钩中获取购物车小计
【发布时间】:2021-05-15 23:08:01
【问题描述】:

我想在 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 hook 内获得不带货币的购物车总数吗?

任何帮助和建议都会非常感激。

【问题讨论】:

    标签: php wordpress woocommerce cart hook-woocommerce


    【解决方案1】:

    由于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
    }
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 这也是返回价格为 0。我已经尝试过了。
      • 你也试过这个吗? WC()->cart->get_cart_subtotal();
      猜你喜欢
      • 2015-02-03
      • 1970-01-01
      • 1970-01-01
      • 2016-03-14
      • 2017-12-01
      • 2021-07-26
      • 1970-01-01
      • 2014-05-04
      • 1970-01-01
      相关资源
      最近更新 更多