Last active
January 8, 2025 11:51
-
-
Save jorpdesigns/12a2685b2c69ea7dc80d94a961a0eae6 to your computer and use it in GitHub Desktop.
Snippet to add discount to WooCommerce cart
This file contains hidden or 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','woocommerce_custom_discount' ); | |
function woocommerce_custom_discount( $cart ) { | |
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) | |
return; | |
// ADD FLAT RATE DISCOUNT | |
$discount = 5; // Replace 5 with your discount | |
// ADD FEE AS PERCENTAGE OF CART TOTAL | |
$percentage = 0.15; // Replace 0.15 with your percentage | |
$discount = ceil( $cart->cart_contents_total * $percentage ); | |
$cart->add_fee( 'Discount Label', -$discount, false, '' ); // Replace Discount Label with preferred label | |
} | |
// ADD THIS TO PREVENT TAX CALCULATION ON NEGATIVE FEE | |
add_filter( 'woocommerce_cart_totals_get_fees_from_cart_taxes', 'exclude_cart_fees_taxes', 10, 3 ); | |
function exclude_cart_fees_taxes( $taxes, $fee, $cart ) { | |
return array(); | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you! The 'woocommerce_cart_totals_get_fees_from_cart_taxes' filter saved my day. However, in my case, I also needed to add a tax-inclusive additional fee for another payment method, so I used the filter like this: