WC_Abstract_Order::apply_coupon()publicWC 3.2.0

Apply a coupon to the order and recalculate totals.

Метод класса: WC_Abstract_Order{}

Хуки из метода

Возвращает

true|WP_Error. True if applied, error if not.

Использование

$WC_Abstract_Order = new WC_Abstract_Order();
$WC_Abstract_Order->apply_coupon( $raw_coupon );
$raw_coupon(строка|WC_Coupon) (обязательный)
Coupon code or object.

Список изменений

С версии 3.2.0 Введена.

Код WC_Abstract_Order::apply_coupon() WC 8.7.0

public function apply_coupon( $raw_coupon ) {
	if ( is_a( $raw_coupon, 'WC_Coupon' ) ) {
		$coupon = $raw_coupon;
	} elseif ( is_string( $raw_coupon ) ) {
		$code   = wc_format_coupon_code( $raw_coupon );
		$coupon = new WC_Coupon( $code );

		if ( $coupon->get_code() !== $code ) {
			return new WP_Error( 'invalid_coupon', __( 'Invalid coupon code', 'woocommerce' ) );
		}
	} else {
		return new WP_Error( 'invalid_coupon', __( 'Invalid coupon', 'woocommerce' ) );
	}

	// Check to make sure coupon is not already applied.
	$applied_coupons = $this->get_items( 'coupon' );
	foreach ( $applied_coupons as $applied_coupon ) {
		if ( $applied_coupon->get_code() === $coupon->get_code() ) {
			return new WP_Error( 'invalid_coupon', __( 'Coupon code already applied!', 'woocommerce' ) );
		}
	}

	$discounts = new WC_Discounts( $this );
	$applied   = $discounts->apply_coupon( $coupon );

	if ( is_wp_error( $applied ) ) {
		return $applied;
	}

	$data_store = $coupon->get_data_store();

	// Check specific for guest checkouts here as well since WC_Cart handles that separately in check_customer_coupons.
	if ( $data_store && 0 === $this->get_customer_id() ) {
		$usage_count = $data_store->get_usage_by_email( $coupon, $this->get_billing_email() );
		if ( 0 < $coupon->get_usage_limit_per_user() && $usage_count >= $coupon->get_usage_limit_per_user() ) {
			return new WP_Error(
				'invalid_coupon',
				$coupon->get_coupon_error( 106 ),
				array(
					'status' => 400,
				)
			);
		}
	}

	/**
	 * Action to signal that a coupon has been applied to an order.
	 *
	 * @param  WC_Coupon $coupon The applied coupon object.
	 * @param  WC_Order  $order  The current order object.
	 *
	 * @since 7.3
	 */
	do_action( 'woocommerce_order_applied_coupon', $coupon, $this );

	$this->set_coupon_discount_amounts( $discounts );
	$this->save();

	// Recalculate totals and taxes.
	$this->recalculate_coupons();

	// Record usage so counts and validation is correct.
	$used_by = $this->get_user_id();

	if ( ! $used_by ) {
		$used_by = $this->get_billing_email();
	}

	$order_data_store = $this->get_data_store();
	if ( $order_data_store->get_recorded_coupon_usage_counts( $this ) ) {
		$coupon->increase_usage_count( $used_by );
	}

	wc_update_coupon_usage_counts( $this->get_id() );

	return true;
}