[wp-trac] [WordPress Trac] #17924: Make Integrating Multiple Roles Per User Easier for Plugin Authors

WordPress Trac noreply at wordpress.org
Mon Mar 3 14:25:58 UTC 2014


#17924: Make Integrating Multiple Roles Per User Easier for Plugin Authors
-----------------------------+-----------------------------
 Reporter:  mobius5150       |       Owner:
     Type:  enhancement      |      Status:  new
 Priority:  normal           |   Milestone:  Future Release
Component:  Role/Capability  |     Version:  3.2
 Severity:  normal           |  Resolution:
 Keywords:  has-patch        |     Focuses:
-----------------------------+-----------------------------

Comment (by nikolov.tmw):

 Replying to [comment:42 landwire]:
 > Replying to [comment:41 nikolov.tmw]:
 >
 > ... Basically making sure that the main role is always the first role in
 array. Or are there any better solutions to accomplish having "main role"
 and "sub roles"? Maybe with key value pairs for the role array? ...

 Hmmm - at this moment besides manually fiddling with the meta that holds
 the user roles after you add/remove a role, I don't see another way. The
 user's roles are stored in an array like this:


 {{{
 array(
     'administrator' => true,
     'custom-role' => true,
     ...
 )
 }}}

 That means that you can do something like

 {{{
 // We need this for WP_User::$cap_key
 $user = new WP_User( $user_id );
 $user_roles = get_user_meta( $user->ID, $user->cap_key, true );
 $main_role = 'custom-role';
 $_user_roles = array();
 $update_roles = false;
 foreach ( $user_roles as $role => $enabled ) {
     if ( $enabled && $role == $main_role ) {
         $_user_roles[ $role ] = $enabled;
         unset( $user_roles[ $role ] );
         $user_roles = array_merge( $_user_roles, $user_roles );
         $update_roles = true;
         break;
     }
 }

 if ( $update_roles ) {
     update_user_meta( $user->ID, $user->cap_key, $user_roles );
 }
 }}}

 You would then have to grab the first role when you access the user's
 roles.

 {{{
 $user = new WP_User( $user_id );
 $main_role = $user->roles[0];
 }}}

 I've tried the above code and it works fine for me.

 Not the best solution, but you can modify the sample plugin I wrote to use
 that code in it - you would have to add a drop-down with all available
 roles to the edit user screen and after the roles are updated use that
 code to shift them around in the desired order.

--
Ticket URL: <https://core.trac.wordpress.org/ticket/17924#comment:43>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform


More information about the wp-trac mailing list