With reference to "Allow specific products to be purchase only if a coupon is applied in Woocommerce" answer code to one of my previous questions, the coupon code is hardcoded in the function and need to match from an existing coupon code in Woocommerce.
But I would like to pick the coupon dynamically from Woocommerce.
How can get the coupon dynamically from woocommerce?
The following code extends my previous answer and will add a checkbox in WooCommerce > coupon section enabling any coupon code to be "mandatory" for specific defined items:
So this way you will not have to define any coupon code in a function.
The whole code:
// Add a custom checkbox to Admin coupon settings pages
add_action( 'woocommerce_coupon_options', 'add_coupon_option_checkbox', 10 );
function add_coupon_option_checkbox() {
woocommerce_wp_checkbox( array(
'id' => 'items_mandatory',
'label' => __( 'Force specific items', 'woocommerce' ),
'description' => __( 'Make this coupon mandatory for specific items.', 'woocommerce' ),
'desc_tip' => false,
) );
}
// Save the custom checkbox value from Admin coupon settings pages
add_action( 'woocommerce_coupon_options_save', 'save_coupon_option_checkbox', 10, 2 );
function save_coupon_option_checkbox( $post_id, $coupon ) {
update_post_meta( $post_id, 'items_mandatory', isset( $_POST['items_mandatory'] ) ? 'yes' : 'no' );
}
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)
$applied_coupons = WC()->cart->get_applied_coupons();
$coupon_applied = false;
if( sizeof($applied_coupons) > 0 ) {
// Loop through applied coupons
foreach( $applied_coupons as $coupon_code ) {
$coupon = new WC_Coupon( $coupon_code );
if( $coupon->get_meta('items_mandatory') === 'yes' ) {
$coupon_applied = true;
break;
}
}
}
// 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
}
}
}
Code goes in functions.php file of your active child theme (or active theme). Tested and works.
And in checkout: