Search code examples
phpwordpresswoocommercecartfee

Add dynamic tiered fee based on cart total in Woocommerce


add_action( 'woocommerce_cart_calculate_fees', 'custom_fee_based_on_cart_total', 10, 1 );
function custom_fee_based_on_cart_total( $cart_object ) {

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

    // The percetage
    $value = 12; // 15%
    // The cart total
    $cart_total = $cart_object->cart_contents_total; 

    // The conditional Calculation
    $fee = $cart_total >= 25 ? $cart_total * $value / 100 : 0;

    if ( $fee != 0 ) 
        $cart_object->add_fee( __( "Kosten MandaBai", "woocommerce" ), $fee, false );
}

Solution

  • Try the following:

    add_action( 'woocommerce_cart_calculate_fees', 'tiered_fee_based_on_cart_total', 10, 1 );
    function tiered_fee_based_on_cart_total( $cart ) {
        if ( is_admin() && ! defined( 'DOING_AJAX' ) ) 
            return;
    
        $total = $cart->cart_contents_total; // The cart total
    
        if( $total < 50 )
            $fee = 8;
        elseif( $total >= 50 && $total < 100 )
            $fee = 10;
        else
            $fee = 12;
    
        if ( $fee != 0 ) 
            $cart->add_fee( __( "Kosten MandaBai", "woocommerce" ), -$fee, false );
    }
    

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