Adding Custom User Role in WordPress

Adding custom user role in WordPress is as easy as it can get. You can pretty much add as many roles as you want and assign various capabilities depending on your requirements. Today, I will show you, how to add a custom role and define it’s capabilities.

WordPress has “add_role” function which can be used to add custom role and to define it’s capabilities using various parameters. Default add_role function looks like this:

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

In this example, I would also use the same function with little twist. So, let’s take a look at the full snippet first.

<?php
function add_custom_role() {
   $caps = array(
      'read' => true, 
      'edit_posts' => true, 
      'delete_posts' => false,);
   add_role('book_author', 'Book Author', $caps); }
   add_action('after_switch_theme', 'add_custom_role');
?>

Now, all you need to do is to copy and paste the snippet above and update your theme’s functions.php file. Now, this function will not create the role until you switch your theme and then get back to your original one. I will explain why in a minute.

What’s going on?

What I am doing here is pretty simple. First I created a function “add_custom_role”. Within the function I declared a variable ($caps) to hold some of the capabilities for the new role. You can add whatever the capability you want to add, just take a look at this table just to get an overall idea first.

Afterwards, I am calling “add_role” function with my desired parameters. That’s pretty much all. However, at the end, I had to decide when to call this function. So, I took the help of an action hook. In this case, I am using “after_switch_theme” action hook instead of “init“. The reason behind not using “init” is that, we need to perform or call this (add_custom_role) function just once. Because these settings gets saved in to the database, so there is no point of calling this function over and over again.

I have used “after_switch_theme” action hook, which would call “add_custom_role” function ONLY after your theme gets activated. So, if you are adding the snippet above on your current theme, you have change your theme and then get back to your original theme just to perform the add_role function.

Once you are done, simply go to the settings menu from your WordPress admin panel and check the drop down menu from “New User Default Role” section. You should find your “Book Author” user added.

Today In History

  •  
  •  

Comment

Leave a Reply

Note: Convet HTML, PHP, JavaScripts from HTMLify, before posting from comment section.
License: By submitting a comment here you grant this site a perpetual license to reproduce your words and name/Web site in attribution. Please use your real name or a pseudonym (i.e., pen name, alias, nom de plume) when commenting. If you add your site name, company name, or something completely random, I'll likely change it to whatever I want.