Skip to content

Instantly share code, notes, and snippets.

@dwanjuki
Forked from dparker1005/one_time_levels.php
Last active August 16, 2023 08:34
Show Gist options
  • Save dwanjuki/fda772ae9e218f858eaabed928ce0e45 to your computer and use it in GitHub Desktop.
Save dwanjuki/fda772ae9e218f858eaabed928ce0e45 to your computer and use it in GitHub Desktop.
Only allow users to have the specified membership levels once
<?php // Copy from below here...
/**
* Only allow users to have the levels specified in $one_time_levels once.
*
* You can add this recipe to your site by creating a custom plugin
* or using the Code Snippets plugin available for free in the WordPress repository.
* Read this companion article for step-by-step directions on either method.
* https://www.paidmembershipspro.com/create-a-plugin-for-pmpro-customizations/
*/
function my_pmpro_registration_checks_one_time_levels( $okay ) {
// Let's only check if things are OK.
if ( ! $okay ) {
return $okay;
}
global $pmpro_level;
// members can only have these levels once
$one_time_levels = array( 6, 7, 8 );
if ( in_array( intval( $pmpro_level->id ), $one_time_levels ) ) {
if ( in_array( intval( $pmpro_level->id ), my_pmpro_get_all_previous_membership_levels_for_user() ) ) {
// User has previously had this level.
pmpro_setMessage( 'You have already purchased this membership level. Please select a different one.', 'pmpro_error' );
$okay = false;
}
}
return $okay;
}
add_action( 'pmpro_registration_checks', 'my_pmpro_registration_checks_one_time_levels' );
/**
* Get all membership levels the user belonged to.
*
* @param mixed $user_id, accepts integer or string.
* @return array $member_previous_levels
*/
function my_pmpro_get_all_previous_membership_levels_for_user( $user_id = null ) {
$member_previous_levels = array();
if ( empty( $user_id ) ) {
$user_id = get_current_user_id();
}
$user_id = intval( $user_id );
if ( is_user_logged_in() ) {
global $wpdb;
$sql_query = "SELECT DISTINCT membership_id FROM $wpdb->pmpro_memberships_users WHERE user_id = '$user_id'";
// Check if user previously belonged to a membership level
$member_previous_levels = $wpdb->get_results( $sql_query, ARRAY_N ); // get levels
$member_previous_levels = array_merge( ...$member_previous_levels ); // flatten multidimensional array
}
return $member_previous_levels;
}
add_filter( 'pmprommpu_gateway_supports_multiple_level_checkout', '__return_false' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment