Justin Rhyne
Justin Rhyne

Reputation: 217

How can I add a custom fee in woocommerce that is calculated after tax

I've added a custom fee to my checkout page with the following code:

add_action( 'woocommerce_cart_calculate_fees','woocommerce_custom_surcharge' );
function woocommerce_custom_surcharge() {
    global $woocommerce;

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

    $percentage = 0.03;
    $surcharge = ( $woocommerce->cart->cart_contents_total + $woocommerce->cart->shipping_total + $woocommerce->cart->tax_total ) * $percentage;
    $woocommerce->cart->add_fee( 'My Fee', $surcharge, false, '' );

}

Everything works as expected except adding in the tax. I thought adding

$woocommerce->cart->tax_total

would do the trick, but that value is returning 0.

Is there some way to calculate tax before this fee is calculated?

Upvotes: 3

Views: 7240

Answers (2)

adamj
adamj

Reputation: 4782

Here's how to grab the total taxes:

$total_taxes = array_sum($woocommerce->cart->get_taxes());

Upvotes: 0

Justin Rhyne
Justin Rhyne

Reputation: 217

I'm not sure if this is the correct way to handle this issue.

But, I've got a working solution to my problem.

I just calculated the tax and added it to the fee calculation.

add_action( 'woocommerce_cart_calculate_fees','woocommerce_custom_surcharge' );
function woocommerce_custom_surcharge() {
global $woocommerce;

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

    $percentage = 0.03;
    $taxes = array_sum($woocommerce->cart->taxes);
    $surcharge = ( $woocommerce->cart->cart_contents_total + $woocommerce->cart->shipping_total + $taxes ) * $percentage;   
    // Make sure that you return false here.  We can't double tax people!
    $woocommerce->cart->add_fee( 'Processing Fee', $surcharge, false, '' );

}

I got the following line from the Woocommerce documentation. Taking care to set the taxable variable to false so as to not double tax people.

$taxes = array_sum($woocommerce->cart->taxes);

Upvotes: 3

Related Questions