Last active
January 15, 2025 23:13
-
-
Save goranefbl/199eff66e209da5db3312578613c620d to your computer and use it in GitHub Desktop.
partial use of coupons
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
add_action('woocommerce_checkout_order_processed', 'handle_partial_coupon_usage', 10, 3); | |
function handle_partial_coupon_usage($order_id, $posted_data, $order) { | |
$applied_coupons = $order->get_coupon_codes(); | |
// Ensure only one coupon is applied | |
if (count($applied_coupons) === 1) { | |
$coupon_code = current($applied_coupons); | |
$coupon = new WC_Coupon($coupon_code); | |
$order_total = $order->get_total(); | |
// Get the total discount applied to the order | |
$total_discount = $order->get_total_discount(); | |
// Calculate the total before discount | |
$total_before_discount = $order_total + $total_discount; | |
$coupon_amount = $coupon->get_amount(); | |
// If coupon amount is greater than order total | |
if ($coupon_amount > $total_before_discount) { | |
// Calculate remaining balance | |
$remaining_balance = $coupon_amount - $total_before_discount; | |
if ($remaining_balance <= 0) { | |
return; | |
} | |
// Update the existing coupon with the remaining balance | |
$coupon->set_amount($remaining_balance); | |
$coupon->save(); | |
// Reset the usage count to 0 | |
$coupon->set_usage_count(0); | |
$coupon->save(); | |
// Add a note to the order about the updated coupon | |
$order->add_order_note(sprintf( | |
'Coupon %s partially used. Remaining balance updated to €%s.', | |
$coupon_code, | |
$remaining_balance | |
)); | |
// Inform the user (this will appear on the thank you page) | |
wc_add_notice(sprintf( | |
'Vous avez utilisé une partie de votre cagnotte. Le solde restant de votre coupon est maintenant de €%s.', | |
$remaining_balance | |
), 'success'); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment