首先向以下角色添加功能
add_action( \'after_setup_theme\', \'add_caps_to_custom_roles\' );
function add_caps_to_custom_roles() {
$caps = array(
\'read_cpt\',
\'edit_cpt\',
\'edit_others_cpt\',
);
$roles = array(
get_role( \'third_party\' ),
get_role( \'data_entry_operator\' ),
);
foreach ($roles as $role) {
foreach ($caps as $cap) {
$role->add_cap( $cap );
}
}
}
那么
/**
* Helper function getting roles that the user is allowed to create/edit/delete \'TP\' post.
*
* @param WP_User $user
* @return array
*/
function allowed_roles_to_edit_TP_post( $user ) {
$allowed = array();
if ( in_array( \'administrator\', $user->roles ) ) { // Admin can edit all roles post
$allowed = array_keys( $GLOBALS[\'wp_roles\']->roles );
} else ( in_array( \'data_entry_operator\', $user->roles ) ) {
$allowed[] = \'third_party\';
}
return $allowed;
}
/**
* Remove roles that are not allowed for the current user role.
*/
function editable_roles( $roles ) {
if ( $user = wp_get_current_user() ) {
$allowed = allowed_roles_to_edit_TP_post( $user );
foreach ( $roles as $role => $caps ) {
if ( ! in_array( $role, $allowed ) )
unset( $roles[ $role ] );
}
}
return $roles;
}
add_filter( \'editable_roles\', \'editable_roles\' );
/**
* Prevent users deleting/editing users with a role outside their allowance.
*/
function controll_map_meta_cap( $caps, $cap, $user_ID, $args ) {
if ( ( $cap === \'read_cpt\' || $cap === \'edit_cpt\' || $cap === \'edit_others_cpt\' ) && $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 ) {
$allowed = allowed_roles_to_edit_TP_post( $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\', \'controll_map_meta_cap\', 10, 4 );