Repository › Forums › Support › WooCommerce Extended Coupon Features PRO › Auto Coupon when a certain item is in the cart › Reply To: Auto Coupon when a certain item is in the cart
May 15, 2023 at 10:29 am #19734
Soft79
Keymaster
Hi,
You need a custom PHP snippet for that. The following snippet will only make the coupon valid if product with id 1234 is in the cart. Replace 1234 with the product id of the item that must be in the cart and replace THE_COUPON_CODE with the actual coupon code. Note: snippet has not been tested.
add_filter( 'woocommerce_coupon_is_valid', function( $valid, $coupon, $wc_discounts ) {
$required_product_id = 1234;
$coupon_code = 'THE_COUPON_CODE';
if ( strcasecmp( $coupon->get_code(), $coupon_code ) !== 0 ) {
return $valid;
}
if ( ! class_exists( 'WJECF_WC_Discounts' ) ) {
return $valid;
}
if ( ! $valid ) {
return $valid;
}
if ( is_null( $wc_discounts ) ) {
$wc_discounts = new WJECF_WC_Discounts( WC()->cart );
}
foreach ( $wc_discounts->get_items() as $item_key => $item ) {
if ( ! $item->product ) {
continue;
}
$product_id = $item->product->get_id();
if ( 'product_variation' == get_post_type( $product_id ) ) {
$product_id = $item->product->get_parent_id();
}
if ( $product_id == $required_product_id ) {
return true;
}
}
return false;
}, 10, 3 );