Created
July 8, 2022 09:01
-
-
Save MrJoshFisher/9187af3eb0f1cd2b5b9f14c3b35ac7d0 to your computer and use it in GitHub Desktop.
[Make Coupon Requirement For 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_check_cart_items', 'mandatory_coupon_for_specific_items' ); | |
function mandatory_coupon_for_specific_items() { | |
$targeted_ids = array(37); // The targeted product ids (in this array) | |
$coupon_code = 'summer2'; // The required coupon code | |
$coupon_applied = in_array( strtolower($coupon_code), WC()->cart->get_applied_coupons() ); | |
// Loop through cart items | |
foreach(WC()->cart->get_cart() as $cart_item ) { | |
// Check cart item for defined product Ids and applied coupon | |
if( in_array( $cart_item['product_id'], $targeted_ids ) && ! $coupon_applied ) { | |
wc_clear_notices(); // Clear all other notices | |
// Avoid checkout displaying an error notice | |
wc_add_notice( sprintf( 'The product"%s" requires a coupon for checkout.', $cart_item['data']->get_name() ), 'error' ); | |
break; // stop the loop | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment