Creating custom user roles in WordPress using the add_role function

The WordPress add_role function is used to add a new user role to a WordPress website. This function can be useful for customizing the permissions and capabilities of different users on the site. By creating custom roles, website administrators can tailor the level of access and control that different users have within the WordPress dashboard and on the front-end of the site. This can help to better manage user permissions and ensure that the right users have the right level of access to the website’s content and functionality.

Parameters for WordPress add_role function

The add_role function in WordPress accepts the following parameters:

  • $role (string, required): Role name.
  • $display_name (string, required): Display name for role.
  • $capabilities (bool[], optional, default value: array()): List of capabilities keyed by the capability name. For example, array( 'edit_posts' => true, 'delete_posts' => false ).

Return Value

The function returns a WP_Role object if the role is added, or void otherwise.

Examples

How to add a custom role in WordPress

Use the add_role function to add a custom role in WordPress.

add_role( 'custom_role', 'Custom Role', array(
 'read' => true,
 'edit_posts' => true,
 'delete_posts' => false,
));

How to add capabilities to a custom role in WordPress

Use the add_role function to add capabilities to a custom role in WordPress.

$role = get_role( 'custom_role' );
$role->add_cap( 'edit_theme_options' );

How to remove a custom role in WordPress

Use the remove_role function to remove a custom role in WordPress.

remove_role( 'custom_role' );

Conclusion

The add_role function is an effective feature for managing user roles in WordPress. It allows developers to easily create and assign custom roles, as well as modify existing roles to fit the specific needs of their project. By leveraging this function, WordPress sites can maintain a high level of security and organization, ensuring that each user has the appropriate level of access and permissions. With its straightforward syntax and extensive customization options, add_role is a valuable asset for any WordPress developer.

Related WordPress Functions