I'm using the below function which currently accepts a single (or array of) static coupon codes. How can I change this to work with any valid (i.e. not already used the maximum times etc.) coupon code that exists in the site?
add_action( 'woocommerce_check_cart_items', 'mandatory_coupon_code' );
function mandatory_coupon_code() {
$product_categories = array( 'gifts' ); // Category ID or slug of targeted category
// NEED TO EDIT THIS PART TO GET THE LIST OF VALID CODES
$coupon_code = 'testing1'; // 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 ){
if( has_term( $product_categories, 'product_cat', $cart_item['product_id'] ) && ! $coupon_applied ) {
wc_clear_notices(); // Clear all other notices
// Avoid checkout displaying an error notice
wc_add_notice( sprintf( 'The product "%s" requires a valid redemption code for checkout.', $cart_item['data']->get_name() ), 'error' );
break; // stop the loop
}
}
}
Edit:
Further to the comments and information from this link, I've tried the below code but this isn't working:
add_action( 'woocommerce_check_cart_items', 'mandatory_coupon_code' );
function mandatory_coupon_code() {
$product_categories = array( 'gifts' ); // Category ID or slug of targeted category
$coupon_code = array();
foreach ( $coupons as $coupon ) {
$coupon_name = $coupon->post_title;
array_push( $coupon_code, $coupon_name );
}
$coupon_applied = in_array( strtolower($coupon_code), WC()->cart->get_applied_coupons() );
// Loop through cart items
foreach ( WC()->cart->get_cart() as $cart_item ){
if( has_term( $product_categories, 'product_cat', $cart_item['product_id'] ) && ! $coupon_applied ) {
wc_clear_notices(); // Clear all other notices
// Avoid checkout displaying an error notice
wc_add_notice( sprintf( 'The product "%s" requires a valid redemption code for checkout.', $cart_item['data']->get_name() ), 'error' );
break; // stop the loop
}
}
}