dots Created with Sketch.
Yogesh Chauhan's Blog

How to add and remove capabilities from a role in WordPress?

in WordPress on July 18, 2021

When you add user roles, you can add capabilities at the same time. But, sometimes you want to add or remove capabilities from a user role that already exists.

How to add capabilities?

To add capabilities to a role, you need to get the role first using get_role() and then add capabilities using add_cap() method.


function guest_editor_caps() {
    // Gets the simple_role role object.
    $role = get_role( 'guest_editor' );
 
    // Add a new capability.
    $role->add_cap( 'edit_others_posts', true );
}
 
// Add simple_role capabilities
// priority must be after the initial role definition.
add_action( 'init', 'guest_editor_caps', 11 );

How to remove capabilities?

All you need to do is change add_cap() method to remove_cap() method in the code above. That’s it.


function guest_editor_caps() {
    // Gets the simple_role role object.
    $role = get_role( 'guest_editor' );
 
    // Add a new capability.
    $role-> remove_cap( 'edit_others_posts', true );
}
 
// Add simple_role capabilities
// priority must be after the initial role definition.
add_action( 'init', 'guest_editor_caps', 11 );

amazon

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Jul 22 Is there a CSS parent selector? #Jul 22 Difference between :where and :is in CSS #Jul 22 Does :is() pseudo selector hint at CSS preprocessing in the future? #Jul 22 Control Scrolling with CSS Scroll Snap #Jul 21 Control rendering using CSS content-visibility property #Jul 21 How to use @supports rule in CSS?
You might also like these
What are keys in React?ReactWhat is the correct way to enqueue multiple CSS files in WordPress?WordPressbin2hex() and chr() String Functions in PHPPHPThe actual difference between indexOf() and search() in JavaScriptJavaScriptOpen Source Security Tools for Defense SecurityMiscellaneousHow to Use SQL MAX() Function with Dates?SQL/MySQLWhat’s a page re-rendering in React?ReactHow to detect the Blog Page in WordPress?WordPressHow to refresh a page using PHP at regularly occurring intervals?PHPWhat is PostgreSQL? How similar or different it is from SQL?PostgresHow to create a simple stopwatch using JavaScript?JavaScriptHow to add multiple components in React app?React