Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Add A Coupon Dynamically based on Cart Subtotal with WooCommerce
<?php
/**
* @snippet Add A Coupon Dynamically based on Cart Subtotal with WooCommerce
* @sourcecode http://hirejordansmith.com
* @author Jordan Smith
* @compatible WooCommerce 2.4.7
*/
add_action( 'woocommerce_before_cart', 'apply_matched_coupons' );
function apply_matched_coupons() {
global $woocommerce;
// Set your coupon codes
$tri10 = 'tri10';
$tri15 = 'tri15';
$tri20 = 'tri20';
// Get the cart subtotal in non-decimal number format
$cart_subtotal = WC()->cart->subtotal;
// If cart subtotal is less than 400 remove coupons
if ($cart_subtotal < 400) {
if ( $woocommerce->cart->has_discount( $tri10 ) || $woocommerce->cart->has_discount( $tri15 ) || $woocommerce->cart->has_discount( $tri20 ) ) {
WC()->cart->remove_coupon( $tri10 );
WC()->cart->remove_coupon( $tri15 );
WC()->cart->remove_coupon( $tri20 );
}
}
// If cart subtotal is greater 399 AND is less than 600 add or remove coupons
if ($cart_subtotal > 399 && $cart_subtotal < 600 ) {
if ( $woocommerce->cart->has_discount( $tri10 ) ) return;
if ( $woocommerce->cart->has_discount( $tri15 ) || $woocommerce->cart->has_discount( $tri20 ) ) {
WC()->cart->remove_coupon( $tri15 );
WC()->cart->remove_coupon( $tri20 );
}
$woocommerce->cart->add_discount( $tri10 );
}
// If cart subtotal is greater than 599 AND is less than 800 add or remove coupons
if ($cart_subtotal > 599 && $cart_subtotal < 800) {
if ( $woocommerce->cart->has_discount( $tri15 ) ) return;
if ( $woocommerce->cart->has_discount( $tri10 ) || $woocommerce->cart->has_discount( $tri20 ) ) {
WC()->cart->remove_coupon( $tri10 );
WC()->cart->remove_coupon( $tri20 );
}
$woocommerce->cart->add_discount( $tri15 );
}
// If cart subtotal is greater than 799 add or remove coupons
if ( $cart_subtotal > 799) {
if ( $woocommerce->cart->has_discount( $tri20 ) ) return;
if ( $woocommerce->cart->has_discount( $tri10 ) || $woocommerce->cart->has_discount( $tri15 ) ) {
WC()->cart->remove_coupon( $tri10 );
WC()->cart->remove_coupon( $tri15 );
}
$woocommerce->cart->add_discount( $tri20 );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.