Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.