LLMS_Voucher::use_voucher( string $code, int $user_id )

Attempt to redeem a voucher for a user with a code


Parameters Parameters

$code

(string) (Required) Voucher code of the voucher being redeemed.

$user_id

(int) (Required) WP_User ID of the user redeeming the voucher.


Top ↑

Return Return

(bool|WP_Error) Error object on failure, true when successful.


Top ↑

Source Source

File: includes/class.llms.voucher.php

	public function use_voucher( $code, $user_id ) {

		$code = sanitize_text_field( $code );

		$voucher = $this->check_voucher( $code );

		if ( ! is_wp_error( $voucher ) ) {

			$this->id = $voucher->voucher_id;

			// Ensure the user hasn't already redeemed this voucher.
			if ( $this->get_redemptions_for_code_by_user( $voucher->id, $user_id ) ) {

				return new WP_Error( 'error', __( 'You have already redeemed this voucher.', 'lifterlms' ) );

			}

			// Get products linked to the voucher.
			$products = $this->get_products();

			if ( ! empty( $products ) ) {

				// Loop through all of them and attempt enrollment.
				foreach ( $products as $product ) {

					llms_enroll_student( $user_id, $product, 'voucher' );

				}

				/**
				 * Perform action before voucher redeemed.
				 *
				 * Action to perform before the voucher redeemed.
				 *
				 * @since 2.2.1
				 * @since 3.24.1 Added $voucher_title parameter.
				 * @since 3.27.0 Changed $voucher_title to $voucher_code to fix undefined property notice.
				 *
				 * @param int    $voucher_id   Voucher id of the voucher being redeemed.
				 * @param int    $user_id      WP_User ID of the user redeeming the voucher.
				 * @param string $voucher_code Voucher code of the voucher being redeemed.
				 */
				do_action( 'llms_voucher_used', $voucher->id, $user_id, $voucher->code );

				// Use voucher code.
				$data = array(
					'user_id' => $user_id,
					'code_id' => $voucher->id,
				);
				$this->save_redeemed_code( $data );

				return true;

			}
		} else {

			return $voucher;

		}

	}


Top ↑

Changelog Changelog

Changelog
Version Description
3.27.0 Unknown.
2.0.0 Introduced.

Top ↑

User Contributed Notes User Contributed Notes

You must log in before being able to contribute a note or feedback.