Search code examples
phpwordpresswoocommercecartcoupon

Conditionally adding a cart fee if no coupons are applied to cart


In WooCommerce, I am trying to figured out how to add a "Handling Fee" to every order when no coupons or promo codes are applied to cart.

Here's my "Fee" or "Handling Charge" code:

    add_action( 'woocommerce_cart_calculate_fees','endo_handling_fee' );

function endo_handling_fee() {

global $woocommerce;

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

     $fee = 2.00;
     $woocommerce->cart->add_fee( 'Handling', $fee, true, 'standard' );
}

Any ideas?

Thanks


Solution

  • Here I get the array of cart applied coupons and if there is no coupons applied to cart, then a fee is applied to cart.

    Here is that code:

    add_action( 'woocommerce_cart_calculate_fees','conditional_handling_fee' );
    function conditional_handling_fee() {
    
        if ( is_admin() && ! defined( 'DOING_AJAX' ) )
            return;
    
        // Get the applied coupons + the count (in cart)
        $applied_coupons_arr = WC()->cart->get_applied_coupons();
        $applied_coupons_count = count($applied_coupons_arr);
    
        $fee = 2.00;
    
        if( 0 == $applied_coupons_count )
            WC()->cart->add_fee( 'Handling - '.$applied_coupons_count, $fee, true, 'standard' );
    
    }
    

    Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

    This code is tested and works.


    Reference: WC_Cart class - get_applied_coupons() method