Search code examples
phpwordpresswoocommercecartfee

Simple weight based taxable fee for a specific country in Woocommerce


In Woocommerce, I use following block of code that adds a custom fee in cart and checkout, based on total weight for a specific country:

function weight_add_cart_fee() {

    // Set here your percentage
    $percentage = 0.17;

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // Get weight of all items in the cart
    $cart_weight = WC()->cart->get_cart_contents_weight();

    // calculate the fee amount
    $fee = $cart_weight * $percentage;

    // If weight amount is not null, adds the fee calcualtion to cart

    global $woocommerce;
    $country = $woocommerce->customer->get_country();
    if ( !empty( $cart_weight ) && $country == 'SK'  ) { 
        WC()->cart->add_fee( __('Recyklačný poplatok (podľa váhy): ', 'my_theme_slug'), $fee, false );
    }
}
add_action( 'woocommerce_cart_calculate_fees','weight_add_cart_fee' );

But I need to make this fee taxable. How to make it taxable?.


Solution

  • There is some mistakes and your code is outadated. Try the following instead (with a taxable fee):

    add_action( 'woocommerce_cart_calculate_fees','add_fee_weight_based', 10 , 1 );
    function add_fee_weight_based( $cart ) {
        if ( is_admin() && ! defined( 'DOING_AJAX' ) )
            return;
    
        $percentage       = 0.17; // Percentage
        $targeted_country = 'SK'; // Country
        $cart_weight      = $cart->get_cart_contents_weight(); // Total weight
       
    
        if ( $cart_weight > 0 && WC()->customer->get_shipping_country() == $targeted_country ) {
            $cart->add_fee( __('Recyklačný poplatok (podľa váhy): ', 'my_theme_slug'), ($cart_weight * $percentage), true );
        }
    }
    

    Code goes in function.php file of your active child theme (or active theme). Tested and works.

    Make a fee taxable

    To make a fee taxable, in the WC_Cart add_fee() method, you need to set the 3rd argument to true (taxable)…

    The 4th optional argument is related to the tax class that you can specify if you need to set a specific tax class