When new user register then add new user role

I’m trying to do custom function when new user register then adds new user role, new user role is the username.

For example, when user register and the username is apple, It will automatically create a role called Apple and assign to Apple user.

add_action( 'user_register', 'add_new_role' );

function add_new_role() {
 $result = add_role(
    'user_name',
    __( 'user_name' ),
    array(
        'read'         => true,  // true allows this capability
        'edit_posts'   => true,
        'delete_posts' => false, // Use false to explicitly deny
    )
);

}

This code can be implemented when a new user is registered and create a role called username, I don’t know how to get the username from the form and I want it automatically assign the new role to the new user.

Thank you for the help.

2 Answers
2

The user_register hook passes the parameter $user_id to your function. Get the login name after instantiating a user object with get_userdata( $user_id ).

Update the assigned user role with wp_update_user. Alternatively, you can use add_role to assign the new role in addition to the currently assigned role instead of removing the currently defined role with wp_update_user.

add_action( 'user_register', 'abc_assign_role' );

function abc_assign_role( $user_id ) {
    // Instantiate user object.
    $userobj = get_userdata( $user_id );
    // Define new role using the login name of this user object.
    $new_role = $userobj->user_login;

    // Create the role.
    add_role(
        $new_role,
            __( $new_role ),
            array(
            'read'         => true,
            'edit_posts'   => true,
            'delete_posts' => false,
            )
    );

    // Assign a new role to this user, replacing the currently assigned role.
    wp_update_user( array( 'ID' => $user_id, 'role' => $new_role ) );
    // Assign additional role to the user, leaving the default role that is currently assigned to the user.
    // $userobj->add_role( $new_role );
}

Leave a Comment