Back to Top

How to add and remove user capabilities in woocommerce

Updated 5 June 2024

When you install a WordPress site, you also create a users with administrator. In this tutorial, I will show you how to add and remove capabilities of different roles in wordpress.

In order to manage roles and capabilities effectively there are five function in wordpress

  • add_role(): Enables you to add a custom role.
  • remove_role(): Enables you to remove a custom role.
  • add_cap(): Enables you to add a custom capability to a role.
  • remove_cap(): Enables you to remove a custom capability from a role.
  • get_role(): Gets information about a role as well as the capabilities associated with the role.

Why we need to add and remove capability

WordPress comes with a built-in user with their roles and capabilities.

If you run a wordpress blog with multiple authors and you want to remove and give access to authors for specific roles so they cannot perform it and you don’t want that author delete(trash) their published post .

function wk_remove_author_capabilities() {
$author = get_role( 'author' );
   if(empty(wk_get_current_user())){
       $author->remove_cap( 'delete_published_posts' );
   }else {
       $author->add_cap( 'delete_published_posts' );
   }
}

add_action( 'admin_init', 'wk_remove_author_capabilities' );

Here you can see we add capability to the author when function (wk_get_current_user) return something otherwise it will remove the author capability.

Searching for an experienced
Woocommerce Company ?
Find out More
remove capabilities of different roles

You can clearly see that trash button from the published post is disappeared.

How to remove multiple capabilities of the user?

In this example i’ll show you how manipulate multiple capabilities at same time, here we remove the capability of deleting the post and pages from the author .

function wk_remove_author_capabilities() {
$author = get_role( 'author' );
$capability = array(
'delete_posts',
'delete_private_pages',
'delete_private_posts',
'delete_published_pages',
'delete_published_posts',
);
foreach ( $capability as $cap ) {
    $author->remove_cap( $cap );
    }
}

add_action( 'admin_init', 'wk_remove_author_capabilities');

Note: If you want to add capability just replace ( remove_cap ) with ( add_cap ).

This is all about add and remove user capabilities.

References : https://developer.wordpress.org/

Thank You!

If you need custom WordPress Development services then feel free to reach us and also explore our exclusive range of WooCommerce Extensions.

!!Have a Great Day Ahead!!

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Back to Top

Message Sent!

If you have more details or questions, you can reply to the received confirmation email.

Back to Home