0

I'm trying to add an additional role for a user when they register if they register as a specific role.

Here is my function:

function add_secondary_role( $user_id ) {
    $current_user = wp_get_current_user();
    if ( in_array( 'um_dueling-pianist', (array) $current_user->roles ) ) {
        $user = get_user_by('id', $user_id);
        $user->add_role('pianist');
    } 
}

It doesn't work. I have registered a test account with the role 'um_dueling-pianist' and it does not add the other role of 'pianist.' Those are both the meta values for the user roles and not the display name of the user roles.

Any idea what's wrong with my function?

1

You check the role not for the created user, only the currently logged in user. Try this way:

add_action( 'user_register', 'se333727_additional_roles' );

function se333727_additional_roles( $user_id )
{
    $new_user = get_user_by( 'ID', $user_id );
    if ( in_array( 'um_dueling-pianist', (array)$new_user->roles ) ) {
        $new_user->add_role('pianist');
    } 
}
  • That's not working either. I wonder if it's because I use the Ultimate Member plugin for registration? – osakagreg Apr 7 at 20:20
  • Accoring to Ultimate Member their registration action is: add_action( 'um_user_register', 'function_name', 10, 2 ); Unfortunately, that did not remedy the problem. – osakagreg Apr 7 at 20:27
  • Got it! Thanks for your help. I needed to use add_action( 'um_user_register', 'se333727_additional_roles', 10 ); – osakagreg Apr 7 at 20:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.