Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save JBNavadiya/08368a709bd1f570b8db to your computer and use it in GitHub Desktop.
Save JBNavadiya/08368a709bd1f570b8db to your computer and use it in GitHub Desktop.
<?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