Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.