I'm trying to apply a coupon only on products that are on stock.
So if i have 5 items on cart and 4 in stock, just 4 will have the discount applied, the products on backorder WILL NOT.
Actually I'm trying to change the default "get_items_to_apply_coupon
" function in "class-wc-discounts.php
" file.
I've tried calculating the stock quantity of the current product inside foreach cicle and then i've changed the $item_to_apply->quantity
to the difference between stock and cart products.
But also if i put "200" in $->quantity the discount won't change.
protected function get_items_to_apply_coupon( $coupon ) {
$items_to_apply = array();
foreach ( $this->get_items_to_validate() as $item ) {
$item_to_apply = clone $item; // Clone the item so changes to this item do not affect the originals.
if ( 0 === $this->get_discounted_price_in_cents( $item_to_apply ) || 0 >= $item_to_apply->quantity ) {
continue;
}
if ( ! $coupon->is_valid_for_product( $item_to_apply->product, $item_to_apply->object ) && ! $coupon->is_valid_for_cart() ) {
continue;
}
$items_to_apply[] = $item_to_apply;
}
return $items_to_apply;
}
The class-wc-discounts.php
contains
apply_coupon_percent
- Apply percent discount to items and return an array of discounts granted.In this function we find the woocommerce_coupon_get_discount_amount
filter hook.
So when a product is on backorder, you could return 0 as a discount
function filter_woocommerce_coupon_get_discount_amount( $discount, $price_to_discount , $cart_item, $single, $coupon ) {
// On backorder
if ( $cart_item['data']->is_on_backorder() ) {
$discount = 0;
}
return $discount;
}
add_filter( 'woocommerce_coupon_get_discount_amount', 'filter_woocommerce_coupon_get_discount_amount', 10, 5 );