Hopefully this makes sense. I’m still learning.
There is a function in a plugin I’m developing that I want to modify to recognize custom roles.
My function works when it is hard-coded to accept administrator, editor, author, contributor, and subscriber. However, I’m stuck on modifying the conditional to accept all editable roles.
Here is the working code (but hard-coded):
if ( $current_user->data->wp_capabilities['administrator'] ) {
$role = 'administrator';
} elseif ( $current_user->data->wp_capabilities['editor'] ) {
$role = 'editor';
} elseif ( $current_user->data->wp_capabilities['author'] ) {
$role = 'author';
} elseif ( $current_user->data->wp_capabilities['contributor'] ) {
$role = 'contributor';
} elseif ( $current_user->data->wp_capabilities['subscriber'] ) {
$role = 'subscriber';
}
if ( isset( $role ) ) {
/* If they are an admin then we grant them all permissions that they ask for */
if ( $current_user->data->wp_capabilities['administrator'] ) {
foreach ( $new_caps as $new_cap ) {
$capabilities[ $new_cap ] = true;
}
$user->add_role( $role );
} /* Otherwise lets check if their role deserves that capability */
else {
foreach ( $new_caps as $new_cap ) {
if ( $wp_roles->get_role( $role )->has_cap( $new_cap ) ) {
$capabilities[ $new_cap ] = true;
$user->add_role( $role );
}
}
}
}
Instead of if … administrator then assign role …. it should be a variable.
I’m guessing but somehow editable roles should be available (?) such as the following.
$all_roles = $wp_roles->roles;
$editable_roles = apply_filters('editable_roles', $all_roles);
Can someone help me out and suggest how to rewrite the conditional so it is not hard-coded?
Thank you.
First, your check code works, and takes this pattern:
So lets swap the hardcoded role string out for a variable called
$role_name
( you could call it something else if you want ). The check for a role name is now:But we need to check more than one role, so, lets make a list of the roles to check
Then check each role in our list
So far everything we’ve done has been standard programming, with very little PHP specific knowledge. I recommend you take a good look at for loops and arrays as your question indicates a lack of knowledge or confidence in these areas.
But we’re not finished. You want to be able to handle any arbitrary role!
So lets start with
get_editable_roles()
. This will give us an array of roles, but we can’t swap out the array from above without a slight modification.In your case however you want the roles of a specific user, so going back to your original check, you use this array:
so if we do this for our loop:
You should be able to do what you desire