I've created a new role and I need to give this role the full permissions and capability of an admin less create new admin user and edit plugin/themes. Is possible recall all and remove only the 3 I need, or i have to put 1 by 1 like in the code i posted (edit/delete post)?
$result = add_role( 'Client', 'Client', array(
'read' => true,
'edit_posts' => true,
'delete_posts' => false,
) );
I've created a new role and I need to give this role the full permissions and capability of an admin less create new admin user and edit plugin/themes. Is possible recall all and remove only the 3 I need, or i have to put 1 by 1 like in the code i posted (edit/delete post)?
$result = add_role( 'Client', 'Client', array(
'read' => true,
'edit_posts' => true,
'delete_posts' => false,
) );
Share
Improve this question
edited Feb 3, 2020 at 15:28
DevBeppe
asked Feb 3, 2020 at 15:19
DevBeppeDevBeppe
477 bronze badges
1 Answer
Reset to default 3It sounds like you want to add all the admin capabilities to a role except a few key capabilities that you have in mind. What you could do is get the administrator role and do a key diff on capabilities you do not want. We have to use array_diff_key()
because capabilities are keyed by name:
array( 'edit_plugins' => 1 )
You would only want to do this once though. Either whenever your plugin has been installed or you can do a check if the role exists and return early. Otherwise, whenever the admin role gets new capabilities you may find the new role also gets those same capabilities. An example of that check could look like:
if( role_exists( 'Client' ) ) {
return
}
Below is the function without the above conditional which shows an example of how you could do this:
/**
* Adds are new role based on the administrator role capabilities
*
* @return void
*/
function wpse357776_new_role() {
$admin_role = get_role( 'administrator' );
// Array of capabilities you do not want the new role to have.
$remove_caps = array(
'switch_themes' => 0,
'edit_themes' => 0,
'activate_plugins' => 0,
'edit_plugins' => 0,
'manage_options' => 0,
);
// Run a diff on the admin role capabilities and the removed rules
$my_role_caps = array_diff_key( $admin_role->capabilities, $remove_caps );
// Add the role
$my_role = add_role( 'Client', 'Client', $my_role_caps );
}
add_action( 'after_setup_theme', 'wpse357776_new_role' );