Web DevelopmentWordPress

WordPress dynamically change user capabilities

By May 14, 2015 No Comments

I was looking for an easy way to dynamically add or remove capabilities for users based on either their IDs or roles, but I couldn’t find any elegant solution. That is until I found a beautiful filter:

https://codex.wordpress.org/Plugin_API/Filter_Reference/user_has_cap

It’s so simple, and you can just add this to your functions.php file, or use it in your own plugin:

/**
 * User Capabilities
 * 
 * @see https://codex.wordpress.org/Plugin_API/Filter_Reference/user_has_cap
 */
function jb_user_capabilities( $allcaps, $cap, $args ) {
	// Get current user ID
	$user_id = get_current_user_id();

	// Get current user
	$current_user = get_user_by( 'id', $user_id );

	// Remove capabilities
	if ( in_array( 'administrator', $current_user->roles ) ) {
		$allcaps['activate_plugins'] = false;
		$allcaps['update_core'] = false;
		$allcaps['update_plugins'] = false;
		$allcaps['update_themes'] = false;
		$allcaps['switch_themes'] = false;
		$allcaps['edit_themes'] = false;
		$allcaps['install_plugins'] = false;
		$allcaps['install_themes'] = false;
		$allcaps['delete_themes'] = false;
		$allcaps['delete_plugins'] = false;
		$allcaps['edit_plugins'] = false;
		$allcaps['edit_themes'] = false;
		$allcaps['edit_files'] = false;
		$allcaps['edit_users'] = false;
		$allcaps['create_users'] = false;
		$allcaps['delete_users'] = false;
		$allcaps['list_users'] = false;
	}
	
	return $allcaps;
}
add_filter( 'user_has_cap', 'jb_user_capabilities', 10, 3 );

You can see a list of all roles and capabilities here:
https://codex.wordpress.org/Roles_and_Capabilities

Setting capabilities to “true” enables them, and setting them to “false” disables them. Simple! The above function could be useful when you want to give access to your SEO team, for example. Since this adds or removes capabilities, it is the best way to securely hide menu items in the WP Admin side.

Hope this helps, happy coding! 🙂

Leave a Reply