WC_Discounts::apply_coupon_fixed_cart()protectedWC 3.2.0

Apply fixed cart discount to items.

Method of the class: WC_Discounts{}

No Hooks.

Return

Int. Total discounted.

Usage

// protected - for code of main (parent) or child class
$result = $this->apply_coupon_fixed_cart( $coupon, $items_to_apply, $amount );
$coupon(WC_Coupon) (required)
Coupon object. Passed through filters.
$items_to_apply(array) (required)
Array of items to apply the coupon to.
$amount(int)
Fixed discount amount to apply in cents. Leave blank to pull from coupon.
Default: null

Changelog

Since 3.2.0 Introduced.

WC_Discounts::apply_coupon_fixed_cart() code WC 8.7.0

protected function apply_coupon_fixed_cart( $coupon, $items_to_apply, $amount = null ) {
	$total_discount = 0;
	$amount         = $amount ? $amount : wc_add_number_precision( $coupon->get_amount() );
	$items_to_apply = array_filter( $items_to_apply, array( $this, 'filter_products_with_price' ) );
	$item_count     = array_sum( wp_list_pluck( $items_to_apply, 'quantity' ) );

	if ( ! $item_count ) {
		return $total_discount;
	}

	if ( ! $amount ) {
		// If there is no amount we still send it through so filters are fired.
		$total_discount = $this->apply_coupon_fixed_product( $coupon, $items_to_apply, 0 );
	} else {
		$per_item_discount = absint( $amount / $item_count ); // round it down to the nearest cent.

		if ( $per_item_discount > 0 ) {
			$total_discount = $this->apply_coupon_fixed_product( $coupon, $items_to_apply, $per_item_discount );

			/**
			 * If there is still discount remaining, repeat the process.
			 */
			if ( $total_discount > 0 && $total_discount < $amount ) {
				$total_discount += $this->apply_coupon_fixed_cart( $coupon, $items_to_apply, $amount - $total_discount );
			}
		} elseif ( $amount > 0 ) {
			$total_discount += $this->apply_coupon_remainder( $coupon, $items_to_apply, $amount );
		}
	}
	return $total_discount;
}