diff --git a/adminpages/discountcodes.php b/adminpages/discountcodes.php index 1475e47a4..cf32d4bd9 100644 --- a/adminpages/discountcodes.php +++ b/adminpages/discountcodes.php @@ -68,6 +68,7 @@ $expires_day = intval($_POST['expires_day']); $expires_year = intval($_POST['expires_year']); $uses = intval($_POST['uses']); + $one_use_per_user = ! empty( $_POST['one_use_per_user'] ) ? 1 : 0; //fix up dates $starts = date("Y-m-d", strtotime($starts_month . "/" . $starts_day . "/" . $starts_year, $now )); @@ -81,13 +82,15 @@ 'code' => $code, 'starts' => $starts, 'expires' => $expires, - 'uses' => $uses + 'uses' => $uses, + 'one_use_per_user' => $one_use_per_user ), array( '%d', '%s', '%s', '%s', + '%d', '%d' ) ); @@ -446,7 +449,7 @@ - + - - - + + + +

+ + +

+ + + + + - -

+ one_use_per_user ) ) checked( $code->one_use_per_user, 1 ); ?> /> + diff --git a/includes/functions.php b/includes/functions.php index b709d1c2a..cae94b1bc 100644 --- a/includes/functions.php +++ b/includes/functions.php @@ -1890,7 +1890,7 @@ function pmpro_getDiscountCode( $seed = null ) { * Is a discount code valid - $level_id could be a scalar or an array (or unset) */ function pmpro_checkDiscountCode( $code, $level_id = null, $return_errors = false ) { - global $wpdb; + global $wpdb, $current_user; $error = false; $dbcode = false; @@ -1942,6 +1942,16 @@ function pmpro_checkDiscountCode( $code, $level_id = null, $return_errors = fals } } + // check if this code is limited to one use per user + if ( ! $error ) { + if ( ! empty( $dbcode->one_use_per_user ) && ! empty( $current_user->ID ) ) { + $used = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->pmpro_discount_codes_uses WHERE code_id = '" . esc_sql( $dbcode->id ) . "' AND user_id = '" . esc_sql( $current_user->ID ) . "'" ); + if ( $used > 0 ) { + $error = __( 'You have already used the discount code provided.', 'paid-memberships-pro' ); + } + } + } + // if a level was passed check if this code applies if ( ! $error ) { $pmpro_check_discount_code_levels = apply_filters( 'pmpro_check_discount_code_levels', true, $dbcode->id ); diff --git a/includes/upgradecheck.php b/includes/upgradecheck.php index 2665ba1ac..fbc13dd1b 100644 --- a/includes/upgradecheck.php +++ b/includes/upgradecheck.php @@ -392,6 +392,15 @@ function pmpro_checkForUpgrades() { pmpro_upgrade_3_2(); update_option( 'pmpro_db_version', '3.2' ); } + + /** + * Version 3.4 + * Adding `one_use_per_user` column to discount codes. + */ + if ( $pmpro_db_version < 3.4 ) { + pmpro_db_delta(); + update_option( 'pmpro_db_version', '3.4' ); + } } function pmpro_db_delta() { @@ -567,6 +576,7 @@ function pmpro_db_delta() { `starts` date NOT NULL, `expires` date NOT NULL, `uses` int(11) NOT NULL, + `one_use_per_user` tinyint(4) NOT NULL DEFAULT '0', PRIMARY KEY (`id`), UNIQUE KEY `code` (`code`), KEY `starts` (`starts`),