add_role

Home » Functions » add_role

Function Name: add_role

In WordPress, roles are used to determine what actions a user is allowed to perform on a website. By default, WordPress comes with a set of predefined roles such as Administrator, Editor, Author, Contributor, and Subscriber. However, there may be cases where you need to create custom roles with specific capabilities to suit your website’s needs. This is where the add_role() function comes in handy.

The add_role() function allows you to create a new user role with specific capabilities. You can specify the name, display name, and capabilities of the role. This function is an administrator-level function and can only be used by users with the ‘manage_roles’ capability.

Here is the syntax for the add_role() function:

add_role( $role, $display_name, $capabilities );

Parameters:

  • $role (string) (required): The name (slug) of the role. This should be unique.
  • $display_name (string) (required): The display name of the role.
  • $capabilities (array) (optional): An array of capabilities that the role should have.

Example Usage: Let’s say you want to create a new role called "Content Manager" with the capabilities to edit and publish posts, but not delete them. You could use the following code:

function add_content_manager_role() { $capabilities = array( ‘edit_posts’ => true, ‘publish_posts’ => true, ‘delete_posts’ => false, ); add_role( ‘content_manager’, ‘Content Manager’, $capabilities ); } add_action( ‘init’, ‘add_content_manager_role’ );

This code creates a new role with the name "content_manager", display name "Content Manager", and the capabilities to edit and publish posts, but not delete them.

In summary, the add_role() function is a powerful tool for creating custom user roles with specific capabilities for your WordPress website.

Learn More on WordPress.org

Register an account to save your snippets or go Pro to get more features.