php - 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?
Answer
Solution:
In
woocommerce_cart_calculate_fees
action hook,WC()->cart->total
always return0
, as this hook is fired before the cart total calculations…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:
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.