Last active
October 7, 2024 07:39
-
-
Save daveloodts/2ff15712d9910dcfbe98e8fbccf471de to your computer and use it in GitHub Desktop.
WooCommerce coupons and shipping costs
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_cart_calculate_fees', 'apply_coupon_to_shipping', 10, 1); | |
function apply_coupon_to_shipping($cart) { | |
if (is_admin() && !defined('DOING_AJAX')) { | |
return; | |
} | |
// Get the applied coupon(s) | |
$coupons = $cart->get_applied_coupons(); | |
// Get cart subtotal and shipping cost including tax | |
$cart_subtotal = WC()->cart->get_subtotal() + WC()->cart->get_subtotal_tax(); | |
$shipping_cost = $cart->get_shipping_total() + $cart->get_shipping_tax(); // Shipping total including tax | |
$cart_subtotal = number_format($cart_subtotal, 2, '.', ''); | |
// Check if there are applied coupons | |
if (!empty($coupons)) { | |
// Loop through the applied coupons | |
foreach ($coupons as $coupon_code) { | |
$coupon = new WC_Coupon($coupon_code); | |
$original_discount = $coupon->get_amount(); // Get the original discount value | |
$discount_type = $coupon->get_discount_type(); // Get discount type (fixed/cart percentage, etc.) | |
// Format the original discount to 2 decimal places | |
$original_discount_formatted = number_format($original_discount, 2, '.', ''); | |
// Get the total discount amount applied by this coupon | |
$discount_total = WC()->cart->get_cart_discount_total(); // Total discount amount applied by coupons | |
// Check if the discount is greater than the cart subtotal | |
if ($original_discount_formatted > $cart_subtotal) { | |
$remaining_discount = $original_discount_formatted - $cart_subtotal; | |
$remaining_discount_incl_shipping = $remaining_discount - $shipping_cost; | |
if ($remaining_discount_incl_shipping > 0) { | |
$cart->add_fee('Resterend bedrag Coupon lalal', -$shipping_cost); | |
} elseif ($remaining_discount_incl_shipping <= 0) { | |
$need_to_pay = (($cart_subtotal + $shipping_cost) - $original_discount_formatted); | |
$shipping_tax_amount = WC()->cart->get_shipping_tax(); | |
$shipping_tax_percentage = (($shipping_tax_amount / ($shipping_cost - $shipping_tax_amount)) * 100); | |
$shipping_tax_percentage = number_format($shipping_tax_percentage, 0, '.', ''); | |
$shipping_tax_cal = ((100 + $shipping_tax_percentage) / 100); | |
$shipping_discount_fee = $shipping_cost - $need_to_pay; | |
$shipping_discount_fee = $shipping_discount_fee / $shipping_tax_cal; | |
if ($shipping_discount_fee > 0) { | |
$cart->add_fee('Resterend bedrag Coupon', -$shipping_discount_fee, true, 'BTW vrij'); | |
} | |
} | |
} | |
} | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment