Quantcast
Channel: wordpress – lessthanweb.
Viewing all articles
Browse latest Browse all 25

Add Custom Capabilities To User Roles

$
0
0

In the Add New User Role post, we have created a new WordPress role with default WordPress capabilities.

In this how-to we will add new custom capability to the existing WordPress role Contributor. In other words, contributor will be able to sit at the kings table as a thank you for all the contributions that they made so far. ;)

First off, if you want to add a new capability to a custom role, you should use the add_role function as shown here. If however you want to add a new capability to the existing role, use add_cap method.

The add_cap accepts two parameters, capability name and optional parameter grant capability (true or false).

If you want to use add_cap method, you first need to get the role that you want to add new capability as add_cap method is part of the WP_Roles class. To get the existing role use the function get_role.

function lessthanweb_assign_new_capability() {
	//	Get Contributor role
	$contributor = get_role( 'contributor' );

    //	Now we call the WP_Roles method with our custom capability :)
    $contributor->add_cap( 'can_sit_at_kings_table', true );
}
register_activation_hook( __FILE__, 'lessthanweb_assign_new_capability' );

That’s it, if you now create a new user and assign Contribution role to the user, he will have our little new fancy custom capability.

To remove the custom capability from role, use remove_cap.

function lessthanweb_remove_capability() {
	//	Get Contributor role
	$contributor = get_role( 'contributor' );

	//	Simply call the function with the capability name.
	$contributor->remove_cap( 'can_sit_at_kings_table' );
}
register_deactivation_hook( __FILE__, 'lessthanweb_remove_capability' );

Do note that modifying capabilities requires WordPress to run a few SQL queries so that the changes are permanent and as such it is recommended to do this modifications on plugin or theme activation or deactivation.

Also a fair note would be to never modify the default capabilities as a lot of plugins and themes might depend on the default settings. If you want to make modifications, create a new role or simply add new capabilities.


Viewing all articles
Browse latest Browse all 25

Trending Articles