How to Change Role Capabilities in WordPress

Home » Snippets » How to Change Role Capabilities in WordPress
0

Created with:

Visibility: 

public

Creator: WPTurbo Team

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project

Are you looking to customize the capabilities and permissions of different user roles on your WordPress site? By default, WordPress provides a set of predefined roles such as Administrator, Editor, Author, and Subscriber, each with their own set of capabilities. However, there may be instances where you need to modify the capabilities assigned to a specific role or create a completely new role with custom capabilities. In this article, we will guide you through the process of changing role capabilities in WordPress, allowing you to tailor the user experience and access levels to meet your specific needs.

					function wpturbo_change_role_capabilities() {
    $role = get_role( 'subscriber' ); // replace 'subscriber' with the desired role slug
    $role->add_cap( 'edit_posts' ); // add the desired capability
    $role->remove_cap( 'upload_files' ); // remove an existing capability
}
add_action( 'init', 'wpturbo_change_role_capabilities' );
				

The code snippet above demonstrates how to customize the capabilities of a user role in WordPress. In this example, we are specifically targeting the "subscriber" role (you can replace this with the desired role slug).

To begin, we define a function called wpturbo_change_role_capabilities(). Inside this function, we retrieve the role object using the get_role() function. We pass in the role’s slug as a parameter, in this case, "subscriber".

Next, we use the role object’s add_cap() method to add a new capability to the role. In this example, we are granting the "edit_posts" capability to the "subscriber" role. This will allow users assigned to this role to edit posts within the WordPress admin.

Similarly, you can use the remove_cap() method to remove an existing capability from the role. In this example, we are removing the "upload_files" capability from the "subscriber" role.

By hooking the wpturbo_change_role_capabilities() function to the init action, we ensure that this code is executed when WordPress is initialized.

This code snippet can be valuable when you need to customize the capabilities of a specific user role to meet the requirements of your website or application. It allows you to grant or revoke specific privileges to different user roles, giving you greater control over the capabilities of your WordPress site.

Register an account to save your snippets or go Pro to get more features.