diff --git a/includes/class-wc-discounts.php b/includes/class-wc-discounts.php index b03694947b..9bd4f28dac 100644 --- a/includes/class-wc-discounts.php +++ b/includes/class-wc-discounts.php @@ -499,11 +499,28 @@ protected function apply_coupon_fixed_cart( $coupon, $items_to_apply, $amount = * @return int Total discounted. */ protected function apply_coupon_custom( $coupon, $items_to_apply ) { + $limit_usage_qty = 0; + $applied_count = 0; + + if ( null !== $coupon->get_limit_usage_to_x_items() ) { + $limit_usage_qty = $coupon->get_limit_usage_to_x_items(); + } + + // Apply the coupon to each item. foreach ( $items_to_apply as $item ) { - $discounted_price = $this->get_discounted_price_in_cents( $item ); + // Find out how much price is available to discount for the item. + $discounted_price = $this->get_discounted_price_in_cents( $item ); + + // Get the price we actually want to discount, based on settings. $price_to_discount = wc_remove_number_precision( ( 'yes' === get_option( 'woocommerce_calc_discounts_sequentially', 'no' ) ) ? $discounted_price : $item->price ); - $discount = wc_add_number_precision( $coupon->get_discount_amount( $price_to_discount / $item->quantity, $item->object, true ) ) * $item->quantity; - $discount = min( $discounted_price, $discount ); + + // See how many and what price to apply to. + $apply_quantity = $limit_usage_qty && ( $limit_usage_qty - $applied_count ) < $item->quantity ? $limit_usage_qty - $applied_count : $item->quantity; + $apply_quantity = max( 0, apply_filters( 'woocommerce_coupon_get_apply_quantity', $apply_quantity, $item, $coupon, $this ) ); + + // Run coupon calculations. + $discount = wc_add_number_precision( $coupon->get_discount_amount( $price_to_discount / $item->quantity, $item->object, true ) ) * $apply_quantity; + $discount = wc_round_discount( min( $discounted_price, $discount ), 0 ); // Store code and discount amount per item. $this->discounts[ $coupon->get_code() ][ $item->key ] += $discount;