How to assign an additional/extra/second user-role to multiple users (of a specific user-role)

You should be able to do this yourself by writing a simple function and hooking it it onto a user-related action (whether you want to do this once or on an ongoing basis will be up to you).

There are a couple different ways to trigger it, but perhaps the simplest I can think of would be to hook into the profile_update hook so that it would get run every time a user is saved. You could also hook into user_register so it runs everytime a new user is added to ensure your data stays in sync. In order to test this out, then, you would want to try saving an existing user or creating a new user, as this will trigger the action hook.

add_action( 'profile_update', 'wpse_assign_abc_role_to_xyz_users', 10 );
add_action( 'user_register', 'wpse_assign_abc_role_to_xyz_users', 10 );

function wpse_assign_abc_role_to_xyz_users() {
   $args = array(
        'role'         => 'xyz', // Set the role you want to search for here
        'role__not_in' => array( 'abc' ), // If they already have abc role, we can skip them
        'number'       => '500', // Good idea to set a limit to avoid timeouts/performance bottlenecks
    ); 
    $xyz_users = get_users( $args );

    // Bail early if there aren't any to update
    if ( count( $xyz_users ) === 0 ) return;

    // get_users() returns an array of WP_User objects, meaning we can use the add_role() method of the object

    foreach ( $xyz_users as $user ) {
        $user->add_role( 'abc' );
    }
}

This would assume that you have already added the abc role using add_role so that WP is aware of it.

Unfortunately, I am not available to test it right now but I will try and test later, however this should get you steered in the right direction.

Leave a Comment