首先,您需要向Doctor
和Receptionist
角色添加以下功能:
list_users
edit_users
create_users
delete_users
现在我们可以将工作与控制这些,他们可以创建用户/ edite /删除。让我们从“ helper”函数开始,该函数将返回允许用户编辑的角色:
/**
* Helper function get getting roles that the user is allowed to create/edit/delete.
*
* @param WP_User $user
* @return array
*/
function wpse_188863_get_allowed_roles( $user ) {
$allowed = array();
if ( in_array( 'administrator', $user->roles ) ) { // Admin can edit all roles
$allowed = array_keys( $GLOBALS['wp_roles']->roles );
} elseif ( in_array( 'Doctor', $user->roles ) ) {
$allowed[] = 'Receptionist';
$allowed[] = 'Guest';
} elseif ( in_array( 'Receptionist', $user->roles ) ) {
$allowed[] = 'Guest';
}
return $allowed;
}
并设置他们可以分配用户的角色:
/**
* Remove roles that are not allowed for the current user role.
*/
function wpse_188863_editable_roles( $roles ) {
if ( $user = wp_get_current_user() ) {
$allowed = wpse_188863_get_allowed_roles( $user );
foreach ( $roles as $role => $caps ) {
if ( ! in_array( $role, $allowed ) )
unset( $roles[ $role ] );
}
}
return $roles;
}
add_filter( 'editable_roles', 'wpse_188863_editable_roles' );
最后,根据角色限制可以编辑/删除的用户:
/**
* Prevent users deleting/editing users with a role outside their allowance.
*/
function wpse_188863_map_meta_cap( $caps, $cap, $user_ID, $args ) {
if ( ( $cap === 'edit_user' || $cap === 'delete_user' ) && $args ) {
$the_user = get_userdata( $user_ID ); // The user performing the task
$user = get_userdata( $args[0] ); // The user being edited/deleted
if ( $the_user && $user && $the_user->ID != $user->ID /* User can always edit self */ ) {
$allowed = wpse_188863_get_allowed_roles( $the_user );
if ( array_diff( $user->roles, $allowed ) ) {
// Target user has roles outside of our limits
$caps[] = 'not_allowed';
}
}
}
return $caps;
}
add_filter( 'map_meta_cap', 'wpse_188863_map_meta_cap', 10, 4 );
Doctors
,Receptionist
并且Guest
也无法编辑自己的个人资料。我希望他们编辑自己的个人资料。我怎样才能做到这一点?