WC_Cart::check_customer_coupons()publicWC 1.0

Check for user coupons (now that we have billing email). If a coupon is invalid, add an error.

Checks two types of coupons:

  1. Where a list of customer emails are set (limits coupon usage to those defined).
  2. Where a usage_limit_per_user is set (limits coupon usage to a number based on user ID and email).

Method of the class: WC_Cart{}

No Hooks.

Return

null. Nothing (null).

Usage

$WC_Cart = new WC_Cart();
$WC_Cart->check_customer_coupons( $posted );
$posted(array) (required)
Post data.

WC_Cart::check_customer_coupons() code WC 8.6.1

public function check_customer_coupons( $posted ) {
	foreach ( $this->get_applied_coupons() as $code ) {
		$coupon = new WC_Coupon( $code );

		if ( $coupon->is_valid() ) {

			// Get user and posted emails to compare.
			$current_user  = wp_get_current_user();
			$billing_email = isset( $posted['billing_email'] ) ? $posted['billing_email'] : '';
			$check_emails  = array_unique(
				array_filter(
					array_map(
						'strtolower',
						array_map(
							'sanitize_email',
							array(
								$billing_email,
								$current_user->user_email,
							)
						)
					)
				)
			);

			// Limit to defined email addresses.
			$restrictions = $coupon->get_email_restrictions();

			if ( is_array( $restrictions ) && 0 < count( $restrictions ) && ! $this->is_coupon_emails_allowed( $check_emails, $restrictions ) ) {
				$coupon->add_coupon_message( WC_Coupon::E_WC_COUPON_NOT_YOURS_REMOVED );
				$this->remove_coupon( $code );
			}

			$coupon_usage_limit = $coupon->get_usage_limit_per_user();
			if ( 0 < $coupon_usage_limit && 0 === get_current_user_id() ) {
				// For guest, usage per user has not been enforced yet. Enforce it now.
				$coupon_data_store = $coupon->get_data_store();
				$billing_email     = strtolower( sanitize_email( $billing_email ) );
				if ( $coupon_data_store && $coupon_data_store->get_usage_by_email( $coupon, $billing_email ) >= $coupon_usage_limit ) {
					if ( $coupon_data_store->get_tentative_usages_for_user( $coupon->get_id(), array( $billing_email ) ) ) {
						$coupon->add_coupon_message( WC_Coupon::E_WC_COUPON_USAGE_LIMIT_COUPON_STUCK_GUEST );
					} else {
						$coupon->add_coupon_message( WC_Coupon::E_WC_COUPON_USAGE_LIMIT_REACHED );
					}
				}
			}
		}
	}
}