Paid Memberships Pro: Cap the Number of Members per Level
Closes checkout for a level once it reaches the number of active members you set, perfect for limited founding-member or cohort offers.
Opens WPIDE on
Code
if ( ! function_exists( 'pmpro_setMessage' ) ) {
return;
}
// Level ID => maximum active members.
$wpide_pmpro_level_caps = array(
3 => 100,
);
add_filter( 'pmpro_registration_checks', function ( $continue ) use ( $wpide_pmpro_level_caps ) {
global $wpdb, $pmpro_level;
$level_id = isset( $pmpro_level->id ) ? (int) $pmpro_level->id : ( isset( $_REQUEST['level'] ) ? absint( $_REQUEST['level'] ) : 0 );
if ( ! $continue || empty( $wpide_pmpro_level_caps[ $level_id ] ) || pmpro_hasMembershipLevel( $level_id ) ) {
return $continue;
}
$key = 'wpide_pmpro_count_' . $level_id;
$count = get_transient( $key );
if ( false === $count ) {
$count = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(DISTINCT user_id) FROM {$wpdb->pmpro_memberships_users} WHERE membership_id = %d AND status = 'active'", $level_id ) );
set_transient( $key, $count, 10 * MINUTE_IN_SECONDS );
}
if ( $count >= $wpide_pmpro_level_caps[ $level_id ] ) {
pmpro_setMessage( 'Sorry, this membership is full. Please join the waiting list or choose another level.', 'pmpro_error' );
return false;
}
return $continue;
} );
add_action( 'pmpro_after_change_membership_level', function ( $level_id ) {
delete_transient( 'wpide_pmpro_count_' . (int) $level_id );
} );
Notes
Counts active members of the level, cached for 10 minutes. Existing members can still renew.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.