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

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
Introduction to Angular modules Part 2: NgModules and componentsAngularCONCAT and CONCAT_WS Functions in PostgresPostgresSome Useful Operators in The SQL WHERE ClauseSQL/MySQLUse eq() method in jQueryjQueryWhat are CSS Specificity Rules and how does browser apply them?CSSAngular 9 time clock update every minute, second, hourAngularThe flex-grow, flex-shrink and flex-basis Properties in CSSCSSWordPress: How to print ACF repeater field values?WordPressHow to add and remove list items using JavaScript?JavaScriptIs there a CSS parent selector?CSSHAVING Clause in Postgres with Examples in All Aggregate FunctionsPostgresWhat are Google Web Stories and How to create them in WordPress?WordPress