Skip to content
Advertisement

How to make a custom cart fee to be taxable in WooCommerce

Found exactly the snippet I was looking for to add a fixed fee amount to each individual cart item regardless of price. This site sells tires. So each tire will be charged 3$.

Here is the code I’m using and works:

add_action('woocommerce_cart_calculate_fees', function() {
    if (is_admin() && !defined('DOING_AJAX')) {
        return;
    }

    $feetot = WC()->cart->get_cart_contents_count();

    WC()->cart->add_fee(__('Specific Duty on New Tires', 'txtdomain'), 3 * $feetot);
});

I’m not very good with PHP and I’m learning as I go. I did spend 3 hours trying to modify this code so that the $3 fee would be TAXED as well. But I couldn’t figure it out.

Below is what I tried as one of the attempts to have the fee taxed as well but it doesn’t work:

add_action('woocommerce_cart_calculate_fees', function() {
    if (is_admin() && !defined('DOING_AJAX')) {
        return;
    }
    
    $feetot = WC()->cart->get_cart_contents_count();

    WC()->cart->add_fee(__('Specific Duty on New Tires', 'txtdomain', $taxable = true, $tax_class = ''), 3 * $feetot);
});

What I am doing wrong? Any help please.

Advertisement

Answer

To make it work, replace in your code the line:

WC()->cart->add_fee(__('Specific Duty on New Tires', 'txtdomain', $taxable = true, $tax_class = ''), 3 * $feetot);

with the following code line (see WC_Cart add_fee() method):

WC()->cart->add_fee( __('Specific Duty on New Tires', 'text_domain'), $feetot * 3, true, '' );

So your correct hooked function code will be:

add_action('woocommerce_cart_calculate_fees', 'custom_cart_items_fee' );
function custom_cart_items_fee( $cart ) {
    if ( is_admin() && ! defined('DOING_AJAX') ) {
        return;
    }

    $fee_amount = $cart->get_cart_contents_count() * 3;

    $cart->add_fee( __('Specific Duty on New Tires', 'text_domain'), $fee_amount, true, '' );
}

Code goes in functions.php file of the active child theme (or active theme). It should works.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement