Skip to content

Instantly share code, notes, and snippets.

@jorpdesigns
Last active July 12, 2021 16:53
Show Gist options
  • Save jorpdesigns/6af5a083d07e64018654ccf3699319e9 to your computer and use it in GitHub Desktop.
Save jorpdesigns/6af5a083d07e64018654ccf3699319e9 to your computer and use it in GitHub Desktop.
Snippet to apply coupon to WooCommerce cart
<?php
add_action( 'woocommerce_before_cart', 'apply_matched_coupons' );
function apply_matched_coupons() {
$coupon_code = 'renewal20'; // Replace with your own coupon code
if ( WC()->cart->has_discount( $coupon_code ) ) return;
// APPLY COUPON WITHOUT ANY CONDITIONS
WC()->cart->apply_coupon( $coupon_code );
wc_print_notices();
// APPLY COUPON IF PRODUCT ID IS IN CART
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$discountedProducts = array( 186, 187, 188 ); // Replace with your own product ids
if ( in_array( $cart_item['product_id'], $discountedProducts ) ) {
WC()->cart->apply_coupon( $coupon_code );
wc_print_notices();
}
}
// APPLY COUPON IF CART TOTAL IS MORE THAN 30
if ( WC()->cart->subtotal > 30 ) ) { // Replace with your own total
WC()->cart->apply_coupon( $coupon_code );
wc_print_notices();
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment