Last active
July 10, 2021 01:53
-
-
Save jplhomer/6383045 to your computer and use it in GitHub Desktop.
Programmatically alter the WooCommerce cart discount total (and apply a new discount) before it's calculated through the woocommerce_calculate_totals hook. Add this code to your Wordpress functions.php file.
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 | |
/** | |
* Programmatically alter the WooCommerce cart discount total (and apply a new discount) before it's calculated | |
* through the woocommerce_calculate_totals hook. | |
* | |
* For example, if you want to apply an arbitrary discount after a certain number of products in the cart, | |
* you can loop through that number and increment it as needed. | |
* | |
* In this example, I increment the discount by $8.85 after every 15 products added to the cart. | |
* | |
* @return void | |
*/ | |
function mysite_box_discount( ) { | |
global $woocommerce; | |
/* Grab current total number of products */ | |
$number_products = $woocommerce->cart->cart_contents_count; | |
$total_discount = 0; | |
$my_increment = 15; // Apply another discount every 15 products | |
$discount = 8.85; | |
if ($number_products >= $my_increment) { | |
/* Loop through the total number of products */ | |
foreach ( range(0, $number_cards, $my_increment) as $val ) { | |
if ($val != 0) { | |
$total_discount += $discount; | |
} | |
} | |
// Alter the cart discount total | |
$woocommerce->cart->discount_total = $total_discount; | |
} | |
} | |
add_action('woocommerce_calculate_totals', 'mysite_box_discount'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey, I'm looking to apply a discount without code. An automatic discount over 100$ ...
Do you know how can I do that ?
Thanks