Hello everyone,
I need your help after two days of unsuccessful research.
I created a promo code for 50 euros off the cart and another for -50%. My problem is that the -50% discount is not being applied to the remaining amount after deducting the 50 euros.
For example, for a cart of 150 euros:
First discount: -50 euros = 100 euros
Then, I would like to apply -50% on this amount, but it doesn’t work.
I asked ChatGPT to create a code (attached), but it doesn’t work. Does anyone have a recommendation? (I’m not a programmer.)
Thank you in advance and have a great evening!
I need your help after two days of unsuccessful research.
I created a promo code for 50 euros off the cart and another for -50%. My problem is that the -50% discount is not being applied to the remaining amount after deducting the 50 euros.
For example, for a cart of 150 euros:
First discount: -50 euros = 100 euros
Then, I would like to apply -50% on this amount, but it doesn’t work.
I asked ChatGPT to create a code (attached), but it doesn’t work. Does anyone have a recommendation? (I’m not a programmer.)
Thank you in advance and have a great evening!
// Apply the coupon 'CODETEST' only to the remaining amount after other discounts
add_action('woocommerce_cart_calculate_fees', 'apply_discount_after_previous_coupon', 20, 1);
function apply_discount_after_previous_coupon($cart) {
// Do nothing in the admin area or during AJAX calls (outside the shop)
if (is_admin() || defined('DOING_AJAX') && DOING_AJAX) {
return;
}
// Check if the coupon 'CODETEST' is applied
if (!in_array('CODETEST', $cart->get_applied_coupons(), true)) {
return; // Do nothing if the coupon is not used
}
// Get the cart's gross subtotal (before taxes and discounts)
$subtotal = $cart->get_subtotal();
// Stop if the subtotal is 0 or invalid
if ($subtotal <= 0) {
return;
}
// Calculate the total discounts applied by other coupons
$total_discounts = 0;
foreach ($cart->get_coupons() as $code => $coupon) {
if ($code !== 'CODETEST') { // Exclude the 'CODETEST' coupon
$total_discounts += $cart->get_coupon_discount_amount($code, false); // Raw discount
}
}
// Calculate the remaining amount after applying other discounts
$remaining_total = $subtotal - $total_discounts;
// Check if the remaining amount is valid
if ($remaining_total <= 0) {
return; // Do nothing if the remaining amount is zero or negative
}
// Calculate the discount for the 'CODETEST' coupon (50% of the remaining amount)
$discount_amount = $remaining_total * 0.50;
// Apply the discount as a negative fee
$cart->add_fee(__('50% Discount (after other coupons)', 'woocommerce'), -$discount_amount);
}