Bulk "Add Role" Action on the Users Screen
Adds "Add role" options to the Bulk actions menu on the Users screen, so you can give a second role to many users at once without replacing their current role.
Opens WPIDE on
Code
add_filter( 'bulk_actions-users', function ( $actions ) {
if ( ! current_user_can( 'promote_users' ) ) {
return $actions;
}
foreach ( get_editable_roles() as $role => $details ) {
if ( 'administrator' !== $role ) {
$actions[ 'wpide_add_role_' . $role ] = sprintf( 'Add role: %s', translate_user_role( $details['name'] ) );
}
}
return $actions;
} );
add_filter( 'handle_bulk_actions-users', function ( $redirect, $action, $user_ids ) {
if ( 0 !== strpos( $action, 'wpide_add_role_' ) ) {
return $redirect;
}
$role = substr( $action, 15 );
if ( 'administrator' === $role || ! array_key_exists( $role, get_editable_roles() ) ) {
return $redirect;
}
$done = 0;
foreach ( array_map( 'intval', (array) $user_ids ) as $user_id ) {
if ( current_user_can( 'promote_user', $user_id ) ) {
( new WP_User( $user_id ) )->add_role( $role );
$done++;
}
}
return add_query_arg( 'wpide_roles_added', $done, $redirect );
}, 10, 3 );
add_action( 'admin_notices', function () {
if ( isset( $_GET['wpide_roles_added'] ) ) {
$count = absint( $_GET['wpide_roles_added'] );
echo '<div class="notice notice-success is-dismissible"><p>' . esc_html( sprintf( _n( 'Role added to %d user.', 'Role added to %d users.', $count ), $count ) ) . '</p></div>';
}
} );
Notes
Only roles you are allowed to assign are offered, never Administrator, and users you cannot promote are skipped.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.