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 );


Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 How to add Read More Read Less Button using JavaScript? #3 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #4 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #5 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
How to convert a number rounding to a specified number of decimals in JavaScript?JavaScript5 Key Principles Of Good Website UsabilityUI/UXWordPress: How to display fields from ACF Flexible Contents?WordPressHow to create two segues with two UIButtons on a single page (Swift 5.0)?SwiftA quick introduction to API, REST API and PostmanMiscellaneousWhat is the difference between float and double?MiscellaneousHow to Check If a Variable is an Integer, a Float, a Number, NaN, an Infinite or a Numeric in PHP?PHPWhat is an API?MiscellaneousHow to create rotating texts using JavaScript and CSS?CSSClean Form Input With These PHP Functions Before Inserting into DatabasePHPObject destructuring in JavaScript: Unpacking fields from objects passed as function parameterJavaScriptConditional operator in JavaScript (aka ternary operator)JavaScript