Discover in this tutorial how to give permissions to a custom WordPress user role using code, without plugins.
By default, WordPress has 5 user roles:
- Subscriber >
( 'subscriber' )
- Contributor > (
'contributor' )
- Author >
( 'author' )
- Editor >
( 'editor' )
- Administrator >
( 'administrator' )
In addition to these, some plugins can add new roles. For example, WooCommerce creates two more:
- Customer
- Store manager
In fact, in a previous tutorial I explained how you can create a new user role with the capabilities you want.
But if you are not using one of the default roles, another easy option is to add the capability you are interested in to that role.
Let’s see how to do it:
Snippet to add a capability to a WordPress user role
To give a new permission to a user role you can use the native add_cap()
function, let’s see an example.
Add the following code at the end of functions.php or in your functionality plugin:
To see this and another 1097 code snippets of this website, login or subscribe here.
With this snippet you first call the role with the name “Contributor” ( 'contributor' )
and then add the ability to add files to the WordPress library.
This is just an example, but you can play with all the capabilities that WordPress allows you. To know them all take a look at its documentation on roles and capabilities.
By the way, the new capability is saved in the database so once you have refreshed the page, which will execute the code, you can delete the snippet.
Conclusion
Now you know how to add a capability to a custom WordPress user role, 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. 😉