Skip to content

Instantly share code, notes, and snippets.

@rameshelamathi
Last active January 4, 2019 14:04
Show Gist options
  • Save rameshelamathi/a1efcff60624e40a295c4e66a069d3f6 to your computer and use it in GitHub Desktop.
Save rameshelamathi/a1efcff60624e40a295c4e66a069d3f6 to your computer and use it in GitHub Desktop.
Automatically apply coupon in WooCommerce based on Cart Subtotal
//How to provide a tiered, cart subtotal based discount automatically in WooCommerce.
//The snippet assumes that you wanted to provide a fixed discount amount
function auto_apply_coupons_based_on_cart_subtotal() {
//NOTE: You must create the coupon codes first for these 5 tiers and replace the coupon code in the respective lines below
//$10 discount for purchases above $100
$get1 = 'MYCOUPON10'; //your coupon code for $10 discount
//$20 discount for purchases above $200 to $300
$get2 = 'MYCOUPON20'; //your coupon code for $10 discount
//$30 discount for purchases above $300 to $400
$get3 = 'MYCOUPON30'; //your coupon code for $10 discount
//$40 discount for purchases above $400 to $500
$get4 = 'MYCOUPON40'; //your coupon code for $10 discount
//$50 discount for purchases above $500
$get5 = 'MYCOUPON50'; //your coupon code for $10 discount
//get the global WooCommerce object
global $woocommerce;
if ( $woocommerce->cart->cart_contents_total >= 100 && $woocommerce->cart->cart_contents_total < 200 ) {
$woocommerce->cart->add_discount( $get1 );
$woocommerce->show_messages();
} elseif ( $woocommerce->cart->cart_contents_total >= 200 && $woocommerce->cart->cart_contents_total < 300 ) {
$woocommerce->cart->add_discount( $get2 );
$woocommerce->show_messages();
} elseif ( $woocommerce->cart->cart_contents_total >= 300 && $woocommerce->cart->cart_contents_total < 400 ) {
$woocommerce->cart->add_discount( $get3 );
$woocommerce->show_messages();
} elseif ( $woocommerce->cart->cart_contents_total >= 400 && $woocommerce->cart->cart_contents_total < 500 ) {
$woocommerce->cart->add_discount( $get4 );
$woocommerce->show_messages();
} elseif ( $woocommerce->cart->cart_contents_total >= 500 ) {
$woocommerce->cart->add_discount( $get5 );
$woocommerce->show_messages();
}
}
//fire the event
add_action( 'woocommerce_before_cart', 'auto_apply_coupons_based_on_cart_subtotal' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment