How to add custom user roles to your theme without using a third party WordPress plugin.
Welcome back to another WordPress tutorial. This time I will show you how to add and create a new Custom User Role and assign its own capabilities. This feature may come up handy if the default WordPress user roles (Author, Subscriber, Editor, etc.) aren’t sufficient for your needs and you want to create a custom one with its own capabilities.
Before we move forward you can preview the final result of the script in the screenshots below.
There are quite a bit of plugin options out there so you might want to go ahead and browse the WordPress.org directory. However, if you are working on a custom solution or you don’t really want to use a plugin you can take a look at the script and use it as a starting point.
I tried to keep the code as simple as I could but there are some additional customizations you might want to remove or replace with your own.
I am loading the Font Awesome 4.7 icons only for demonstration purposes and you may want to remove them if you want to use another method.
However, if you already have them loaded within your plugin or a theme you keep the code as it is.
Note: I suppose you can have the same end result by using the WordPress built-in Dashicons or another method e.g. SVGs, CSS Entities or even Emojis.
For this demo tutorial, I am loading the Custom User Role feature inside my theme functions.php file and adding it as an additional setting under Settings > General.
Of course, you can reuse and tweak the code and apply the same approach to your custom plugin.
There are a few comments added inside the PHP file, but I want to make a couple more clarifications before I show you the actual code.
As I mentioned you may want to edit your custom user roles and to have this you need to tweak a bit the code. The same way I listed the user roles for removal I would create a select dropdown and then populate the existing capabilities for the selected role.
The two WordPress function that will come up handy to create the edit functionality are has_cap() and remove_cap(). Additional information can be found at the WordPress Codex.
Additionally, you may want to reorder the capabilities in the multiple select in a different way.
‘Til the next one.
* We have a NO SPAM policy so you won't reaceive any meaningless emails from us!