Skip to content

Instantly share code, notes, and snippets.

@jorpdesigns
Last active January 8, 2025 11:51
Show Gist options
  • Save jorpdesigns/12a2685b2c69ea7dc80d94a961a0eae6 to your computer and use it in GitHub Desktop.
Save jorpdesigns/12a2685b2c69ea7dc80d94a961a0eae6 to your computer and use it in GitHub Desktop.
Snippet to add discount to WooCommerce cart
<?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();
}
?>
@harslannet
Copy link

harslannet commented Jan 8, 2025

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:

add_filter( 'woocommerce_cart_totals_get_fees_from_cart_taxes', 'exclude_cart_fees_taxes', 10, 3 );
function exclude_cart_fees_taxes( $taxes, $fee, $cart ) {
        $chosen_gateway = WC()->session->get('chosen_payment_method');
		// Reset the tax if bank transfer is selected
		if ($chosen_gateway == 'bacs') {
			return array();
		}
		// Use regular tax calculation for other cases.
		return $taxes;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment