Search code examples
phpwordpresswoocommercecart

Charge a conditional Delivery fee in WooCommerce 3


This is my condition like:

If subtotal <= certain amount && subtotal <= certain amount

So if the subtotal matches this criteria then I want to charge a delivery fee which should also show in the email invoice.

Currently this is my code:

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

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

    $subtotal = $woocommerce->cart->subtotal;
    if(subtotal <= certain amount && subtotal <= certain amount){
        $woocommerce->cart->add_fee( 'Delivery Fees', 5, true, 'standard' );
    } 

}

But it is not showing any thing.

What I am doing wrong?


Solution

  • The problem comes from your condition. it should be instead:

    If subtotal <= amount && subtotal > amount2

    Also your code is a bit old, try it this way (an example of progressive fee):

    add_action( 'woocommerce_cart_calculate_fees','my_delivery_fee', 10, 1 );
    function my_delivery_fee( $wc_cart ) {
    
        if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
    
        $subtotal = $wc_cart->subtotal;
        $fee = 0;
    
        // Progressive fee
        if(subtotal < 25 ){ // less than 25 
            $fee = 5;
        } elseif( subtotal >= 25 && subtotal < 50){ // between 25 and 50
            $fee = 10;
        } else { // From 50 and up 
            $fee = 15;
        }
    
        if( fee > 0 )
            $wc_cart->add_fee( 'Delivery Fees', $fee, true, 'standard' );
    }
    

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

    All code is tested on Woocommerce 3+ and works.