Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Filter roles list in the Members plugin
<?php
/**
* Filter the editable roles array for the current user
*
* This removes the permission for the user to edit certain roles, but still leaves the
* affected roles visible on the Users > Roles screen
*
* @link https://codex.wordpress.org/Plugin_API/Filter_Reference/editable_roles
*
* @param array $roles Data about the current user's editable roles
* @return array The filtered $roles array
*/
add_filter( 'editable_roles', 'my_editable_roles' );
function my_editable_roles( $roles ) {
$current_user = wp_get_current_user();
# do nothing if current user is an administrator
if( in_array( 'administrator', $current_user->roles ) ) {
return $roles;
}
/**
* Loop through the editable roles and remove items as needed
*
* The array keys are the role slugs, and the array values contain detailed
* data about each role
*/
foreach( $roles as $role => $role_data ) {
if( 'administrator' == $role ) {
unset( $roles[ $role ] );
}
}
return $roles;
} # end: my_editable_roles()
<?php
/**
* Below are the lines of code from the Members plugin that allow us to filter
* the list
*/
// Allow devs to filter the items.
$roles = apply_filters( 'members_manage_roles_items', $roles, $this->role_view );
<?php
/**
* Filter the roles table items on the Users > Roles screen
*
* @param array $roles List of role "slugs" being shown in the table
* @param string $role_view View type for current screen (e.g. all, mine, active, etc)
*
* @return array The filtered $roles array
*/
add_filter( 'members_manage_roles_items', 'my_manage_roles_items', 10, 2 );
function my_manage_roles_items( $roles, $role_view ) {
# get the logged-in user
$current_user = wp_get_current_user();
# do nothing if logged-in user is an administrator
if( in_array( 'administrator', $current_user->roles ) ) {
return $roles;
}
# loop through roles and remove the administrator role
foreach( $roles as $k => $role ) {
if( 'administrator' == $role ) {
unset( $roles[ $k ] );
}
}
return $roles;
} # end: my_manage_roles_items()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.