Discover in this tutorial how to create a new custom WordPress user role with the permissions of an existing role, without plugins, using code.
In previous tutorials you have already seen how:
- Adding a custom user role
- Add capabilities to a custom user role
- Remove capabilities from a custom user role
- Remove a user role
So by now and you know that, by default, WordPress has 5 user roles:
- Subscriber
- Contributor
- Author
- Publisher
- Administrator
In addition to these, some plugins can add new roles. For example, WooCommerce creates two more:
- Customer
- Store manager
Even though you already know how to add and remove capabilities, sometimes having to add them manually can be a bit tedious. That’s why it can be very interesting to be able to “inherit” all the capabilities of an existing user role.
Let’s see how to achieve this.
Snippet to create a custom WordPress user role with the same permissions as an existing one
As we saw in a previous tutorial to generate a new user role you can use the native add_role() function, which has the following syntax:
add_role( $role, $display_name, $capabilities );
Where:
- $role: Unique name of the role.
- $display_name: Name displayed in the WordPress administration panel.
- $capabilities: Capabilities of the role.
What we are going to see in this tutorial is how you can use the role capabilities of an existing one.
Below you have several examples that you can apply by adding the snippet you are interested in at the end of the functions.php file or in your functionality plugin:
To see this and another 1097 code snippets of this website, login or subscribe here.
These are just a few examples, but you can play with all the roles and capabilities that WordPress allows you and the plugins that are installed. To know them all take a look at their documentation on Roles and Capabilities.
Conclusion
Now you know how to generate a custom WordPress user role by copying capabilities from an existing one, without plugins, with a simple code snippet.
Any questions? I read you in the comments.
And if you want to give me any suggestion for future tutorials, leave it in the contact form. Advantages of being a subscriber. 😉