Repository › Forums › Support › WooCommerce Extended Coupon Features PRO › Don’t apply other coupon discounts to a BOGO/Free product › Reply To: Don’t apply other coupon discounts to a BOGO/Free product

#15562
anthonyceo
Participant

Very weird. I’m 100% sure it doesn’t have this on my end. Checked $values many times and doesn’t ever contain _wjecf_free_product_coupon. That code doesn’t work on my end with free products in cart.

However, I did create code that works. A lot more complex than I anticipated. And not very efficient. It was annoying. But hey, it works.

add_filter('woocommerce_coupon_is_valid_for_product', 'coupon_is_valid_for_free_product', 10, 4);
function coupon_is_valid_for_free_product($bool, $product, $coupon, $values) {
	// if coupon is a free product coupon, apply it.
	if ($coupon->get_meta('_wjecf_must_select_free_product') === 'yes') {
		return $bool;
	}
	// Get parent of product
	$parent_id = $product->get_parent_id();
	if ( $parent_id > 0 ) {
		$parent_product = wc_get_product( $parent_id );
	} else {
		$parent_product = $product;
	}
	// Get children ids of product
	$children = $parent_product->get_children();
	if (empty($children)) {
		$children[] = $product->id;
	}
	// get cart coupons
	
	$all_coupons = WC()->cart->get_coupons();
	// loop through cart coupons and don't apply non-free product coupons to free products
	foreach ($all_coupons as $c) {
		$product_ids = explode(',', $c->get_meta('_wjecf_free_product_ids'));
		foreach ($children as $id) {
			// If the current product id is in this free product cart coupon, don't apply coupon
			if (in_array($id, $product_ids)) {
				return false;
			}
		}
	}
	return $bool;
	
}