Created
January 3, 2025 06:19
-
-
Save xlplugins/1bb9c43ab05550be6427ab45bbe63e5c to your computer and use it in GitHub Desktop.
automatically apply a coupon code when someone adds a specific product
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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