WC_Discounts::validate_coupon_user_usage_limit()protectedWC 3.2.0

Ensure coupon user usage limit is valid or throw exception.

Per user usage limit - check here if user is logged in (against user IDs). Checked again for emails later on in WC_Cart::check_customer_coupons().

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

Возвращает

true|false.

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

// protected - в коде основоного (родительского) или дочернего класса
$result = $this->validate_coupon_user_usage_limit( $coupon, $user_id );
$coupon(WC_Coupon) (обязательный)
Coupon data.
$user_id(int)
User ID.

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

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

Код WC_Discounts::validate_coupon_user_usage_limit() WC 8.7.0

protected function validate_coupon_user_usage_limit( $coupon, $user_id = 0 ) {
	if ( empty( $user_id ) ) {
		if ( $this->object instanceof WC_Order ) {
			$user_id = $this->object->get_customer_id();
		} else {
			$user_id = get_current_user_id();
		}
	}

	if ( $coupon && $user_id && apply_filters( 'woocommerce_coupon_validate_user_usage_limit', $coupon->get_usage_limit_per_user() > 0, $user_id, $coupon, $this ) && $coupon->get_id() && $coupon->get_data_store() ) {
		$data_store  = $coupon->get_data_store();
		$usage_count = $data_store->get_usage_by_user_id( $coupon, $user_id );
		if ( $usage_count >= $coupon->get_usage_limit_per_user() ) {
			if ( $data_store->get_tentative_usages_for_user( $coupon->get_id(), array( $user_id ) ) > 0 ) {
				$error_message = $coupon->get_coupon_error( WC_Coupon::E_WC_COUPON_USAGE_LIMIT_COUPON_STUCK );
				$error_code    = WC_Coupon::E_WC_COUPON_USAGE_LIMIT_COUPON_STUCK;
			} else {
				$error_message = $coupon->get_coupon_error( WC_Coupon::E_WC_COUPON_USAGE_LIMIT_REACHED );
				$error_code    = WC_Coupon::E_WC_COUPON_USAGE_LIMIT_REACHED;
			}
			throw new Exception( $error_message, $error_code );
		}
	}

	return true;
}