How to assign selected user role to the members of a specific membership (by code)?

There's a Membership 2 Pro and an Events+ plugin running on the site where users are supposed to be able to add events from the front-end. That works if a font-end editing extension is enabled in Events+. Then the "Capabilities" extension of a plugin is used to allow only "Contributors" to add the events, which is fine too.

This, however, should be connected with a Membership 2 Pro plugin in that way that users that sign up for a specific membership are given a contributor role (or capabilities). Unfortunately, the "Membership Capabilities" add-on of Membership 2 Pro doesn't work in this case.

How to make it so that when a user signs up for a specified membership, he/she is automatically given a "contributor" role?

  • Kasia Swiderska

    Hello Yashita,

    Please check this code:

    <?php
    add_action( 'ms_model_relationship_create_ms_relationship_before', 'ms_controller_member_assign_memberships_done_cb', 99, 4 );
    function ms_controller_member_assign_memberships_done_cb( $membership_id, $user_id, $gateway_id, $move_from_id ) {
    	$user = new WP_User( $user_id );
    	switch( $membership_id ){
    		case 1343:
    			$user->set_role( 'editor' );
    			break;
    
    		case 1345:
    			$user->set_role( 'author' );
    			break;
    
    		case 1348:
    			$user->set_role( 'administrator' );
    			break;
    	}
    }

    This part

    case 1343:
    			$user->set_role( 'editor' );
    			break;

    allows to assign membership ID with the role for the user. You would need to change it for contributor and use your memberships ID.
    Code can be used in functions.php or as Must Use plugin https://premium.wpmudev.org/manuals/wpmu-manual-2/using-mu-plugins/

    kind regards,
    Kasia

Thank NAME, for their help.

Let NAME know exactly why they deserved these points.

Gift a custom amount of points.