Removing a User Role in WordPress

Capability of adding custom role in WordPress is one of many WordPress features that I fell in love with. I have worked on few projects as well where I had to add custom role and define there capabilities. On my last WordPress tutorial, I have shown how to add custom user role in WordPress.

However, today I will show you how to remove roles (both default and custom) from a site. This fairly simple compare to creating a new role. So, before we get started I want to remind you the "add_role" function. I am doing it for a valid reason, trust me.

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

Now, as you can see that add_role function takes three different parameters. The $role parameter is our main focus. We would always be using the value of this parameter to remove roles from the site.

Let's take a look at the sample function to remove a user role.

As I mentioned earlier, we would need the value for $role parameter in order to remove user role from WordPress.

Removing Default User Role

WordPress creates quite a few default user roles during the installation process, roles like subscriber, author, administrator etc. are some of them. So, let's say you want to remove "subscriber" role from your site. You easily use the following code.

<?php remove_role('subscriber'); ?>

Once you are done with copying and pasting the code on your theme's functions.php file, simply update the page and refresh any page from the front-end. It should delete the "subscriber" user role from your site. As the role gets deleted feel free to delete the code from your functions.php file as well. You don't need to perform this over and over again.

Removing Custom User Role

Let's say you have a custom user role called "book_author" and you want to delete it. The easiest solution should be something like this.

<?php remove_role('book_author'); ?>

However, if you are developing a custom theme and adding a custom user role for a client's site, it might be a good idea to create a function and call that function with an action hook. Let's take a look at the following snippet.

function remove_custom_role() {
   remove_role('book_author'); }
   add_action('switch_theme', 'remove_custom_role');

I am using "switch_theme" action hook with my "remove_custom_role" function. What is happening over here is, as soon as your client switches the theme remove_custom_role function would be called and it will remove the "book_author" role. How you want to do it, it's entirely up to you. Thanks.


Commenting is disabled.