Categories: How To // Wordpress

Add New User Role

Roles! Roles? Yes, roles! But I’m not talking about the movie roles that I have been in, none actually. I’m talking about WordPress roles.

In WordPress you can create new roles with different capabilities and add users to it. Neat right? Hard to do? No!

So let’s take a quick look at the two functions that we are going to use to create and remove new WordPress role.

The first function is called add_role and is used as the name suggests to add a new role.

Function accepts 3 parameters, role name, display name and optional capabilities.

The second function that we are going to use is remove_role. Can you guess what that one does?

The remove_role accepts only one parameter and that is the role name that you wish to remove.

Now there are many ways people create new roles but the proper way is to register new role when you activate a plugin and remove role when you deactivate the plugin.

Why is that? Because when you add new role, settings are saved into certain tables and you really do not want another SQL query being run every single time your site is loaded. Do it properly, do it once. ;)

Can this functions be used in themes too? Well, yes, but you really should not add this kind of functionality to a theme, themes should contain presentation functions. But that’s another story.

So let’s create our new role.

/**
 * Create new user role on plugin activation.
 *
 * @param	void 
 * @return	void
 *
 */
function lessthanweb_create_new_role() {
	//	Call the function for creating new role and set some capabilities.
	add_role( 'king', __( 'King Himself', 'lessthanweb' ), array( 
		'delete_posts' => true, 
		'delete_published_posts' => true, 
		'edit_published_posts' => true, 
		'published_posts' => true, 
		'read' => true, 
		'upload_files' => true, 
	) );
}
register_activation_hook( __FILE__, 'lessthanweb_create_new_role' );

That’s it, we added new role with internal name of “kind”, public name “King Himself” and we have added standard WordPress capabilities to the role.

Now you should be able to assign this role to users.

To remove the role, we simply call the remove_role function in deactivation function.

/**
 * Remove the role we made on plugin activation.
 *
 * @param	void 
 * @return	void
 *
 */
function lessthanweb_remove_role() {
	//	Simply call the function with the role name.
	remove_role( 'king' );
}
register_deactivation_hook( __FILE__, 'lessthanweb_remove_role' );

And that’s it, your plugin will now create new role on activation and remove it when the plugin is deactivated.

What happens to the user who was assigned to the custom role after we remove the role? Well the user will lose all the rights on the site. So it is useful to first change the role of the users who are using your role to something else before removing it.

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *