Search code examples
phpwordpresswoocommercecartfee

Trying to hide the add fee text if criteria is met in WooCommerce


I have a code that i found here on stackoverflow for WooCommerce that allows to add an extra fee if the order is under a set value.

(in this example i have the value ten, everything under that value will add the difference as an procesing tax)

I would like to hide the text in the order page if the the sum of the order is over that set value.

Here is the code:

function woo_add_cart_fee() {

    global $woocommerce;

    $subt = $woocommerce->cart->subtotal;

    if ($subt < 10 ) { 
        $surcharge = 10 - $subt;
    } else { 
        $surcharge = 0;
    }   

    $woocommerce->cart->add_fee( __('Procesing tax for under 10 dolars', 'woocommerce'), $surcharge );

}

add_action( 'woocommerce_cart_calculate_fees', 'woo_add_cart_fee' );

Thank you


Solution

  • global $woocommerce is not necessary because you have access to $cart.

    Adding the fee can be included in the if condition

    function woo_add_cart_fee( $cart ) {
        if ( is_admin() && ! defined( 'DOING_AJAX' ) )
            return;
    
        // Get subtotal
        $subt = $cart->get_subtotal();
    
        // Below
        if ($subt < 10 ) {
            $surcharge = 10 - $subt;
    
            $cart->add_fee( __( 'Procesing tax for under 10 dolars', 'woocommerce' ), $surcharge );
        }
    }
    add_action( 'woocommerce_cart_calculate_fees', 'woo_add_cart_fee', 10, 1 );