使用“woocommerce_product_get_tax_class”钩子时,“WC()->cart->get_subtotal()”返回 0

问题描述

当小计超过特定金额时,我正在尝试取消购物车商品的增值税。但是当我使用 WC()->cart->get_subtotal() 获取小计价格时,它返回 0 并且我的 if 语句失败。

add_action( 'woocommerce_product_get_tax_class','wp_check_uk_vat',1,2 );
    
function wp_check_uk_vat( $tax_class,$product ) {

    $cart_total = WC()->cart->get_subtotal();
    // echo $cart_total;

    if( $cart_total >= 100 ) {

        $tax_class = "Zero rate";

    }

    return $tax_class;

}

这里使用了类似的代码https://docs.woocommerce.com/document/setting-up-taxes-in-woocommerce/#section-18

代码的目标是在订单金额超过 135 英镑时降低购物车上的增值税(而非运费)(以符合针对商家的新英国退欧规则)。

因为 WC()->cart->get_subtotal() 返回 0,所以 if 语句失败,并且不会取消增值税。

解决方法

试试这个

add_action( 'woocommerce_product_get_tax_class','wp_check_uk_vat',1,2 );

function wp_check_uk_vat( $tax_class,$product ) {

    if(WC()->cart){
    $subtotal = 0;
    foreach ( WC()->cart->get_cart() as $cart_item ) {
        $subtotal += $cart_item[ 'data' ]->get_price( 'edit' ) * $cart_item[ 'quantity' ];
    }

    if ( $subtotal >= 100 ) {

        $tax_class = "Zero rate";
    }
    }
    return $tax_class;
}