How To Add a Custom User Role With Specific Capabilities

This code enables you to very easily create custom user roles once added to your functions file.

If you want to make a membership site using code rather than plugins, this code should come in handy.

The code uses the add_role function built into WordPress which includes 3 basic parameters.

  1. role
  2. Display Name
  3. capabilities
add_role('role', 'Display Name',array( 'capabilities' ));

Here’s the most basic working example:

add_role('member', 'Member',array( 'read' => true ));

Now when you go to Users > Add New > Add New User, you’ll find the new role added to the drop down menu next to Role.

Add New User Role

The code creates a new role named Member.

The Member role only allows users assigned this role to read posts.

You can easily add more capabilities like this:

add_role( 'member', 'Member',array( 
    'read' => true,  
    'edit_posts' => true, 
) );

The code in this tutorial enables you to separate subscribers from members.

If you only want to create a new role for logged in members and restrict access to the Dashboard, you can do so with this code:

add_action( 'after_setup_theme','add_custom_role' );
function add_custom_role(){

add_role( 'member', 'Logged In Members',array( 'read' => true ));

}

You can then wrap your content in shortcodes to restrict access to content for logged in members only or based on user role.

Note: Once you have added the code to create a new role, it is saved to your database like any of the default roles so you can remove it from your functions file and use add_cap or remove_cap to modify the capabilities if needed.

You can see the core add-role function in WordPress > wp-includes > capabilities.php.


Comments

One response to “How To Add a Custom User Role With Specific Capabilities”

  1. Arjun Megan Avatar
    Arjun Megan

    I found your link from wordpress dashboard ! Thanks for the post on To create custom user roles !
    I have tried this and could create with ease! 🙂

Leave a Reply