WordPress at Your Fingertips
function is not described

WC_Discounts::validate_coupon_usage_limit() protected WC 3.2.0

Ensure coupon usage limit is valid or throw exception.

{} It's a method of the class: WC_Discounts{}

No Hooks.

Return

true|false.

Usage

// protected - for code of main (parent) or child class
$result = $this->validate_coupon_usage_limit( $coupon );
$coupon(WC_Coupon) (required)
Coupon data.

Changelog

Since 3.2.0 Introduced.

Code of WC_Discounts::validate_coupon_usage_limit() WC 5.7.1

protected function validate_coupon_usage_limit( $coupon ) {
	if ( ! $coupon->get_usage_limit() ) {
		return true;
	}
	$usage_count           = $coupon->get_usage_count();
	$data_store            = $coupon->get_data_store();
	$tentative_usage_count = is_callable( array( $data_store, 'get_tentative_usage_count' ) ) ? $data_store->get_tentative_usage_count( $coupon->get_id() ) : 0;
	if ( $usage_count + $tentative_usage_count < $coupon->get_usage_limit() ) {
		// All good.
		return true;
	}
	// Coupon usage limit is reached. Let's show as informative error message as we can.
	if ( 0 === $tentative_usage_count ) {
		// No held coupon, usage limit is indeed reached.
		$error_code = WC_Coupon::E_WC_COUPON_USAGE_LIMIT_REACHED;
	} elseif ( is_user_logged_in() ) {
		$recent_pending_orders = wc_get_orders(
			array(
				'limit'       => 1,
				'post_status' => array( 'wc-failed', 'wc-pending' ),
				'customer'    => get_current_user_id(),
				'return'      => 'ids',
			)
		);
		if ( count( $recent_pending_orders ) > 0 ) {
			// User logged in and have a pending order, maybe they are trying to use the coupon.
			$error_code = WC_Coupon::E_WC_COUPON_USAGE_LIMIT_COUPON_STUCK;
		} else {
			$error_code = WC_Coupon::E_WC_COUPON_USAGE_LIMIT_REACHED;
		}
	} else {
		// Maybe this user was trying to use the coupon but got stuck. We can't know for sure (performantly). Show a slightly better error message.
		$error_code = WC_Coupon::E_WC_COUPON_USAGE_LIMIT_COUPON_STUCK_GUEST;
	}
	throw new Exception( $coupon->get_coupon_error( $error_code ), $error_code );
}