MemberPress: Add a Role While a Membership Is Active
Gives members an extra WordPress role when they buy a membership and removes it when that membership expires, so role-based plugins can follow MemberPress.
Opens WPIDE on
Code
if ( ! class_exists( 'MeprUser' ) ) {
return;
}
// Membership ID => role.
$wpide_mepr_roles = array(
123 => 'contributor',
);
add_action( 'mepr-event-transaction-completed', function ( $event ) use ( $wpide_mepr_roles ) {
$txn = $event->get_data();
$role = $wpide_mepr_roles[ (int) $txn->product_id ] ?? '';
$user = get_userdata( (int) $txn->user_id );
if ( $role && $user && get_role( $role ) ) {
$user->add_role( $role );
}
} );
add_action( 'mepr-event-transaction-expired', function ( $event ) use ( $wpide_mepr_roles ) {
$txn = $event->get_data();
$role = $wpide_mepr_roles[ (int) $txn->product_id ] ?? '';
$user = get_userdata( (int) $txn->user_id );
if ( ! $role || ! $user || count( $user->roles ) < 2 ) {
return;
}
$member = new MeprUser( $user->ID );
if ( ! $member->is_already_subscribed_to( (int) $txn->product_id ) ) {
$user->remove_role( $role );
}
} );
Notes
The role must exist. It is only removed when the member no longer has any active transaction for that membership.
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.