Getting user roles, not their capabilities, and disabling default user roles
-
Hello,
In my project I’ve defined some new roles using add_role() so that I can display content to users based on their custom roles. Some roles are identical in their capabilities… it’s only the content that they can access that differentiates between them.
I should mention that I’m using the Advanced Custom Fields plugin to create dynamic content fields on custom post types using the Repeater add-on.
The project runs on a WordPress Network installation.
I have two questions:
1. What is the simplest way of getting at the current user’s role?
I found this thread (which is 4 years old): Get a users role by user id which resulted in my current code, which works but relies on users only having one role, and WordPress seems to store roles in an array (I don’t know why).
$current_user = wp_get_current_user(); if ( !empty( $current_user->roles ) && is_array( $current_user->roles ) ) { foreach ( $current_user->roles as $role ) { $current_user_role = $role; } if ($current_user_role == 'administrator') { $user_level = 4; } elseif ($current_user_role == 'custom_level_3') { $user_level = 3; } elseif ($current_user_role == 'custom_level_2') { $user_level = 2; } elseif ($current_user_role == 'custom_level_1') { $user_level = 1; } } else { $current_user_role = 'visitor'; $user_level = 0; }
As you can see, I want to convert the user’s role into an integer so that I can compare to the access level (also an integer) for each section of content.
I am concerned it would break if a user had more than one role for some reason that I don’t understand…
2. What is the best way or removing the default WordPress roles?
In this project, the default roles will be redundant. I am working within functions.php at the moment, although I will probably abstract that user role functionality into a plugin…
Anyway, if I was to use remove_role(), would the default WordPress roles be available when I switch themes or deactivate the plugin?
Thanks,
Andy
- The topic ‘Getting user roles, not their capabilities, and disabling default user roles’ is closed to new replies.