Paid Memberships Pro: Give Each Level Its Own Role
Adds a WordPress role that matches the member's level when they join and removes it when they cancel, expire or change level.
Opens WPIDE on
Code
if ( ! function_exists( 'pmpro_hasMembershipLevel' ) ) {
return;
}
// Level ID => role.
$wpide_pmpro_level_roles = array(
1 => 'contributor',
2 => 'author',
);
add_action( 'pmpro_after_change_membership_level', function ( $level_id, $user_id ) use ( $wpide_pmpro_level_roles ) {
$user = get_userdata( $user_id );
if ( ! $user || user_can( $user, 'manage_options' ) ) {
return;
}
foreach ( $wpide_pmpro_level_roles as $level => $role ) {
if ( ! get_role( $role ) ) {
continue;
}
if ( pmpro_hasMembershipLevel( $level, $user_id ) ) {
$user->add_role( $role );
} elseif ( in_array( $role, (array) $user->roles, true ) && count( $user->roles ) > 1 ) {
$user->remove_role( $role );
}
}
}, 10, 2 );
Notes
The roles must exist. The member's main role is kept, and administrators are never changed.
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.