# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [Memberships](https://wpide.com/library/category/memberships/)
- Requires: MemberPress
- Tags: memberpress, roles, access
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/memberpress-membership-role-sync/

## Code

```php
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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "MemberPress: Add a Role While a Membership Is Active" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
