Skip to content

Instantly share code, notes, and snippets.

@strangerstudios
Last active April 13, 2021 18:32
Show Gist options
  • Save strangerstudios/69d18a410f21bac3a75c to your computer and use it in GitHub Desktop.
Save strangerstudios/69d18a410f21bac3a75c to your computer and use it in GitHub Desktop.
PMPro discount codes can only be used by the same user once.
/*
Discount codes can only be used by the same user once.
Add this to your active theme's functions.php or a custom plugin.
Update the $one_time_use_codes array on line 10.
*/
//check if codes have been used already
function my_pmpro_check_discount_code($okay, $dbcode, $level_id, $code)
{
//define one time use codes
$one_time_use_codes = array('ONCE'); //make them all uppercase
//check if the code being used is a one time code
if(is_user_logged_in() && in_array(strtoupper($code), $one_time_use_codes))
{
//see if user has used this code already
global $current_user;
$used_codes = $current_user->pmpro_used_codes; //stored in user meta
if(is_array($used_codes) && in_array(strtoupper($code), $used_codes))
return "You have already used the discount code provided.";
}
return $okay;
}
add_filter('pmpro_check_discount_code', 'my_pmpro_check_discount_code', 10, 4);
//remember which codes have been used after checkout
function my_pmpro_after_checkout($user_id)
{
global $discount_code;
if(!empty($discount_code))
{
$used_codes = get_user_meta($user_id, 'pmpro_used_codes', true);
if(empty($used_codes))
$used_codes = array();
$used_codes[] = strtoupper($discount_code);
update_user_meta($user_id, "pmpro_used_codes", $used_codes);
}
}
add_action('pmpro_after_checkout', 'my_pmpro_after_checkout');
@laurenhagan0306
Copy link

This recipe is included in the blog post on "Restrict Discount Code Usage to One Time Per User" at Paid Memberships Pro here: https://www.paidmembershipspro.com/restrict-discount-code-one-time-per-user/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment