我想根据整个购物车的小计计算税。在我的例子中,如果subtotal is < 1000
, Tax需要是5%
如果subtotal is >=1000
, Tax需要是12%
我有两个类Reduced rate - 5%
,Standard - 12%
add_action( 'woocommerce_product_variation_get_tax_class', 'wp_check_gst', 1, 2 );
function wp_check_gst( $tax_class, $product )
{
$subtotal = 0;
foreach ( WC()->cart->get_cart() as $cart_item ) {
$subtotal += $cart_item[ 'data' ]->get_price( 'edit' ) * $cart_item[ 'quantity' ];
}
if ( $subtotal >= 1000 )
{
$tax_class = "Standard";
}
if ( $subtotal < 1000 )
{
$tax_class = "Reduced rate";
}
return $tax_class;
}
我使用上面的代码,这似乎不工作??我错过了什么?
您正在使用的钩子不适合该作业。由于要修改影响篮子总数的税类,因此必须使用钩子woocommerce_before_calculate_totals
。你的代码应该是这样的:
add_action( 'woocommerce_before_calculate_totals', 'tax_based_on_cart_subtotal', 10, 1 );
function tax_based_on_cart_subtotal( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
$subtotal = 0;
foreach ( $cart->get_cart() as $cart_item ) {
$subtotal += $cart_item['line_total'];
}
//Standard Tax 12%
if ( $subtotal > 1000 ){
// Change tax class for each cart ietm
foreach ( $cart->get_cart() as $cart_item ) {
$cart_item['data']->set_tax_class( 'standard' );
}
}
//Reduced rate Tax 5%
if ( $subtotal < 1000 ){
// Change tax class for each cart ietm
foreach ( $cart->get_cart() as $cart_item ) {
$cart_item['data']->set_tax_class( 'reduced rate' );
}
}
}