Support » Plugin: Members - Membership & User Role Editor Plugin » Add additional role to user programmatically

  • Resolved Cory

    (@corypina)


    I apologize if this isn’t specific to this plugin, but I have some roles added via Members that I would like to programmatically add to certain users.

    For example, I’ve got a custom role faculty, that I would like to add to certain user upon registration if certain conditions are met. I can’t seem to nail down the right method to run on the user that will give the additional role to the user.

    Is there a function from the plugin I can run to accomplish this?

Viewing 3 replies - 1 through 3 (of 3 total)
  • Plugin Author Caseproof

    (@caseproof)

    Hi Cory,

    To add role on registration you can use this code snippet, modify it, and add at the end of your theme’s functions.php file:

    add_action( 'user_register', function( $user_id ) {
      $user = get_user_by( 'ID', $user_id );
      if ( /* Your condition here */ ) {
        $user->add_role( 'faculty' );
      }
    });

    Hopefully, that helps.

    Thread Starter Cory

    (@corypina)

    Thank you, @caseproof! I’ve actually tried this and it wasn’t working for me, but that just tells me I’ve got some errors somewhere. Thanks for confirming I was on the right track.

    Thread Starter Cory

    (@corypina)

    Update: I definitely just had a few code typos, and this works perfectly. I’m going to forgive myself because it was the first day back after the holiday. 🙂

    Thanks again, @caseproof.

Viewing 3 replies - 1 through 3 (of 3 total)
  • You must be logged in to reply to this topic.