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

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
What are Null Sessions?MiscellaneousCONCAT and CONCAT_WS Functions in PostgresPostgresHow to use @if and @else in SCSS?SCSSHow to host Google fonts on your server and add them using CSS?CSSaddcslashes() and addslashes() String Functions in PHPPHPLearn how to give a temporary name to a column or to a table using SQL AliasesSQL/MySQLWhy do we need HAVING Clause in SQL?SQL/MySQLHow to add menu to your WordPress theme?WordPressThe Difference Between Arrays and Objects in JavaScriptJavaScriptrandom function in SCSS (Sass)SCSSLearn how to use Self JOIN in SQL and MySQLSQL/MySQLWhat is the best way to add JavaScript Code into HTML?HTML