Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save rahuladams/cdf526042ee87f35c10f322233271018 to your computer and use it in GitHub Desktop.
Save rahuladams/cdf526042ee87f35c10f322233271018 to your computer and use it in GitHub Desktop.
add_action( 'woocommerce_before_checkout_form', 'custom_apply_matched_coupons' );
add_action( 'woocommerce_before_cart', 'custom_apply_matched_coupons' );
function custom_apply_matched_coupons() {
$coupon_code = 'coupon_code_here';
$cat_in_cart = false;
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
if ( has_term( 'product-category-slug', 'product_cat', $cart_item['product_id'] ) ) {
$cat_in_cart = true;
break;
}
}
if ( $cat_in_cart && !WC()->cart->has_discount( $coupon_code ) ) {
WC()->cart->apply_coupon( $coupon_code );
wc_print_notices();
}
elseif ( !$cat_in_cart ) {
WC()->cart->remove_coupon( $coupon_code );
wc_print_notices();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment