WordPress как на ладони
Недорогой хостинг для сайтов на WordPress: wordpress.jino.ru Платформа для конвертации и монетизации трафика
функция не описана

WC_Abstract_Order::apply_coupon() public WC 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 4.7.1

<?php
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 seperately 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,
				)
			);
		}
	}

	$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();
	}

	$coupon->increase_usage_count( $used_by );

	return true;
}