Set a Zero tax rate on a cart fee in WooCommerce

2020-08-09 05:52发布

In woocommerce I am adding progressive fee based on product categories with the code below (from this answer thread) and it works well:

add_action( 'woocommerce_cart_calculate_fees', 'wc_custom_surcharge', 20, 1 );
function wc_custom_surcharge( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return; // Exit

    ## Your Settings (below) ##

    $categories      = array(19);
    $targeted_states = array('FL');
    $base_rate       = 1;

    $user_state = WC()->customer->get_shipping_state();
    $user_state = empty($user_state) ? WC()->customer->get_billing_state() : $user_state;
    $surcharge  = 0; // Initializing

    // If user is not from florida we exit
    if ( ! in_array( $user_state, $targeted_states ) )
        return; // Exit

    // Loop through cart items
    foreach ( $cart->get_cart() as $cart_item ) {
        if ( has_term( $categories, 'product_cat', $cart_item['product_id'] )  ){
            // calculating fee based on the defined rate and on item quatinty
            $surcharge += $cart_item['quantity'] * $base_rate;
        }
    }

    // Applying the surcharge
    if ( $surcharge > 0 ) {
        $cart->add_fee( __("State Tire Fee", "woocommerce" ), $surcharge, FALSE, '' );
}

My problem is that I want to set this fee as NOT taxable.

I have tried severals codes and things but just don't get it.

Any help or track will be really appreciated.

1条回答
再贱就再见
2楼-- · 2020-08-09 05:58

You can handle this problem in 2 ways on the available arguments included with the WC_Cart method add_fee():

1) NOT Taxable: Set the fee as "not taxable" (setting the third argument to false):

$cart->add_fee( __("State Tire Fee", "woocommerce" ), $surcharge, false );

2) Taxable with "Zero rate": Set the fee as "taxable" using a the "Zero Rate" tax class.

In this case you need to set (if not done yet) a zero tax rate in Woocommerce Tx settings:

enter image description here

enter image description here

Then you will be able to set in the WC_Cart method add_fee() a taxable fee with the 4th argument set to "Zero rate" which is the tax class, this way:

$cart->add_fee( __("State Tire Fee", "woocommerce" ), $surcharge, true, 'zero-rate' );

On of those should work.

查看更多
登录 后发表回答