WP_Roles::remove_cap()publicWP 2.0.0

Remove capability from role.

Method of the class: WP_Roles{}

No Hooks.

Return

null. Nothing (null).

Usage

global $wp_roles;
$wp_roles->remove_cap( $role, $cap );
$role(string) (required)
Role name.
$cap(string) (required)
Capability name.

Examples

0

#1 Prohibit users with the editor role from reading private posts

The function must be called during the activation of the plugin, i.e. once, not constantly:

function remove_editor_read_private_posts() {

	// get_role returns an instance of the WP_Role class.
	$role = get_role( 'editor' );
	$role->remove_cap( 'read_private_posts' );
}

The same can be done through the WP_Roles class:

function remove_editor_read_private_posts(){
	global $wp_roles;
	$wp_roles->remove_cap( 'editor', 'read_private_posts' );
}
0

#2 Deleting multiple opportunities

Let's remove some features from all users with the "editor" role:

// call the function once, when the plugin/theme is activated
function wpcodex_set_capabilities() {
	// get the role object.
	$editor = get_role( 'editor' );

	//List of features to be removed from the editor
	$caps = array(
		'moderate_comments',
		'manage_categories',
		'manage_links',
		'edit_others_posts',
		'edit_others_pages',
		'delete_posts',
	);

	foreach ( $caps as $cap ) {
		$editor->remove_cap( $cap );
	}
}
0

#3 Removing an option for a specific user

You cannot remove a user right if it belongs to the rights of his role! You can only delete rights that have been added to specific user and go beyond his role. For example, a user with author rights was added the right to edit other users' posts. If you want to remove a user's role permission, you must remove this permission from the role itself. But this change will affect all users with this role.

By default, a user has no rights except those given to him by his role (a user can have several roles at the same time). Therefore, by default, a user cannot have any capabilities removed.

If you want to restrict the user's rights without affecting the rights of his role. Then you need to create a new role, give it all the necessary rights and set this role for the user.

We will remove the ability for user with ID 5 to read private posts only if this permission falls out of his role and it has been added (delegated) for user 5:

$user_id = 5;
$user = new WP_User( $user_id );
$user->remove_cap( 'read_private_posts' );

Changelog

Since 2.0.0 Introduced.

WP_Roles::remove_cap() code WP 6.6.2

public function remove_cap( $role, $cap ) {
	if ( ! isset( $this->roles[ $role ] ) ) {
		return;
	}

	unset( $this->roles[ $role ]['capabilities'][ $cap ] );
	if ( $this->use_db ) {
		update_option( $this->role_key, $this->roles );
	}
}