Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save xlplugins/1bb9c43ab05550be6427ab45bbe63e5c to your computer and use it in GitHub Desktop.
Save xlplugins/1bb9c43ab05550be6427ab45bbe63e5c to your computer and use it in GitHub Desktop.
automatically apply a coupon code when someone adds a specific product
add_action('woocommerce_add_to_cart', 'apply_coupon_on_specific_product');
function apply_coupon_on_specific_product($cart_item_key) {
$product_ids = array(93, 456); // Replace with your specific product IDs
$coupon_code = 'pro2'; // Replace with your coupon code
foreach (WC()->cart->get_cart() as $cart_item) {
if (in_array($cart_item['product_id'], $product_ids)) {
if (!WC()->cart->has_discount($coupon_code)) {
WC()->cart->apply_coupon($coupon_code);
wc_add_notice(sprintf(__('Coupon "%s" has been automatically applied to your cart.', 'woocommerce'), $coupon_code), 'notice');
}
break;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment