WooCommerce Add Fee If Coupon Applied

1.3k Views Asked by At

I'd like to be able to add a fixed $20 fee if a given coupon code (100% off) is applied to the cart. The fee should also not have taxes applied. I'm offering a try at home service for $20, so a certain coupon would discount the cart and all products by 100% but add a $20 fixed fee. Any help is much appreciated!

JC

1

There are 1 best solutions below

4
On

The following code will apply a fee of $20 if a specific coupon code has been applied to cart:

add_action( 'woocommerce_cart_calculate_fees','conditional_custom_fee', 10, 1 );
function conditional_custom_fee( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // HERE set your targeted coupon code (100 % off)
    $coupon_code = 'thatsforfree';

    // Check if our targeted coupon is applied
    if( in_array( wc_format_coupon_code( $coupon_code ), $cart->get_applied_coupons() ) ){
        $title = __('Fee', 'woocommerce'); // The fee title
        $cost  = 20; // The fee amount

        // Adding the fee (not taxable)
        $cart->add_fee( $title, $cost, false );
    }
}

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

The display in cart and checkout pages (on Woocommerce storefront theme):

enter image description here

This code uses The Woocommerce FEE API using WC_Cart method add_fee() with the dedicated action hook woocommerce_cart_calculate_fees.