The get_editable_roles() WordPress PHP function fetches a filtered list of user roles that the current user is allowed to edit.
Usage
$editable_roles = get_editable_roles();
Parameters
- None
More information
See WordPress Developer Resources: get_editable_roles()
Examples
Display a list of editable roles
This example fetches the editable roles and displays them in an unordered list.
$editable_roles = get_editable_roles();
echo '<ul>';
foreach ($editable_roles as $role_name => $role_info) {
echo '<li>' . $role_name . '</li>';
}
echo '</ul>';
Check if a specific role is editable
This example checks if the ‘editor’ role is editable by the current user.
$editable_roles = get_editable_roles();
if (array_key_exists('editor', $editable_roles)) {
echo 'The editor role is editable.';
} else {
echo 'The editor role is not editable.';
}
Get the capabilities of editable roles
This example displays the capabilities of each editable role in nested unordered lists.
$editable_roles = get_editable_roles();
echo '<ul>';
foreach ($editable_roles as $role_name => $role_info) {
echo '<li>' . $role_name;
echo '<ul>';
foreach ($role_info['capabilities'] as $capability => $_) {
echo '<li>' . $capability . '</li>';
}
echo '</ul></li>';
}
echo '</ul>';
Add a new role if it’s not editable
This example adds a new role called ‘custom_role’ with ‘read’ capability if it’s not already editable.
$editable_roles = get_editable_roles();
if (!array_key_exists('custom_role', $editable_roles)) {
add_role('custom_role', 'Custom Role', array('read' => true));
echo 'Custom role added.';
} else {
echo 'Custom role already exists.';
}
Remove an editable role
This example removes the ‘subscriber’ role if it’s editable.
$editable_roles = get_editable_roles();
if (array_key_exists('subscriber', $editable_roles)) {
remove_role('subscriber');
echo 'Subscriber role removed.';
} else {
echo 'Subscriber role not editable.';
}