I Would like in woocommerce cart, that customers will get a 20% discount, but I want to limit the discounted amount to $500 for example.
Is that possible in WooCommerce?
Thanks.
I Would like in woocommerce cart, that customers will get a 20% discount, but I want to limit the discounted amount to $500 for example.
Is that possible in WooCommerce?
Thanks.
This can be done with ease using woocommerce_cart_calculate_fees
hook and the WC_cart method add_fee()
. Then if you use a negative fee, it becomes then a DISCOUNT.
In this function the discount is calculate from the cart subtotal excluding taxes (and you can easily change it to total including taxes).
Here is the code:
add_action( 'woocommerce_cart_calculate_fees', 'custom_limited_discount', 10, 1 );
function custom_limited_discount($cart_object) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Here 20 % of discount
$discount_percent = 0.2;
// Here the max discounted amount
$max_discount = 500;
// Here are some different cart totals
$cart_subtotal_excl_tax = WC()->cart->subtotal_ex_tax;
$cart_subtotal = WC()->cart->subtotal;
$cart_total = WC()->cart->total;
$discount = 0;
// CALCULATION with subtotal excluding taxes
$calculation = $cart_subtotal_excl_tax * $discount_percent;
// Limiting the discount to $max_discount
if ( $calculation > $max_discount ) {
$discount -= $max_discount;
} else {
$discount -= $calculation;
}
$discount_text_output = __( 'Discount (20 %)', 'woocommerce' );
// Adding the discount
$cart_object->add_fee( $discount_text_output, $discount, false );
// Note: Last argument in add_fee() method is related to applying the tax or not to the discount (true or false)
}
This code is tested and is fully functional.
Code goes in function.php file of your active child theme (or theme). Or also in any plugin php files.
Note: Last argument in
add_fee()
method is related to applying the tax or not to the discount (true or false).