nholloway4
nholloway4

Reputation: 230

Add fee based on specific cart total in WooCommerce

I'm trying to add fee based on specific amount in art total. I want to show if the cart total is equal to or greater than total "$$$" amount add the fee, otherwise don't add.

I know this works adding it to total, but I don't think it's checking to see if it is below dollar amount.

function woo_add_custom_fees(){

    $cart_total = 0;

    // Set here your percentage
    $percentage = 0.15;

    foreach( WC()->cart->get_cart() as $item ){ 
        $cart_total += $item["line_total"];
    }
    $fee = $cart_total * $percentage;

    if (  WC()->cart->total >= 25 ) { 

     WC()->cart->add_fee( "Gratuity", $fee, false, '' );

    }

    else {

        return WC()->cart->total;
    }
}
add_action( 'woocommerce_cart_calculate_fees' , 'woo_add_custom_fees' );
add_action( 'woocommerce_after_cart_item_quantity_update', 'woo_add_custom_fees' );

What I am doing wrong?

Upvotes: 3

Views: 14570

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253784

In woocommerce_cart_calculate_fees action hook, WC()->cart->total always return 0, as this hook is fired before the cart total calculations…

You should better use WC()->cart->cart_contents_total instead.

Also the cart object is already included in this hook, so you can add it as an argument in your hooked function.
Also you dont need to use this hook woocommerce_after_cart_item_quantity_update.

Here is your revisited code:

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

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

    // The percentage
    $percent = 15; // 15%
    // The cart total
    $cart_total = $cart->cart_contents_total; 

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

    if ( $fee != 0 ) 
        $cart->add_fee( __( "Gratuity", "woocommerce" ), $fee, false );
}

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

This code is tested and works.

Upvotes: 10

Related Questions