Techniques » WordPress Role Capability Restriction

So you want to restrict user capabilities of a role on your WordPress site from editing and deleting other user’s pages and posts, but you can’t seem to find an easy-to-use plugin that meets your needs, what do you do? Simply restrict that role, with a few lines of code in your theme’s functions.php file, using WordPress’ get_role() and remove_cap() functions. The example below is how to restrict the author role.

1
2
3
4
5
$role = get_role('author');
$role->remove_cap('edit_others_pages');
$role->remove_cap('edit_others_posts');
$role->remove_cap('delete_others_pages');
$role->remove_cap('delete_others_posts');

Pretty simple huh? That’s what I thought when I learned how easily this can be accomplished.

So what’s actually going on with the code? First, we create a variable $role populated with the author’s capabilities. Then we remove the ability of the authors to ‘edit_others_pages’, and other capabilities as desired. This code performs a database change to the role.

NOTE: Once you add this code to your functions.php file and view any page on your site to make the capability changes, you can and should comment it out so that it doesn’t run on every page view.

How do you reverse this you may ask? Simple, use WordPress’ add_cap() function, as if WordPress would let us down.

1
2
3
4
5
$role = get_role('author');
$role->add_cap('edit_others_pages');
$role->add_cap('edit_others_posts');
$role->add_cap('delete_others_pages');
$role->add_cap('delete_others_posts');

This works great when you’ve Created Custom Roles and need to assign capabilities to those new roles.

Below is real-world code we’ve used on a site, and how we left it commented for future reference.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/* Begin Editor Restriction  ****************/
 
/* Enable Restriction Below */
//$role = get_role('editor');
//$role->remove_cap('edit_others_pages');
//$role->remove_cap('edit_others_posts');
//$role->remove_cap('delete_others_pages');
//$role->remove_cap('delete_others_posts');
//$role->remove_cap('manage_links');
//$role->remove_cap('moderate_comments');
 
/* Disable Restriction Below */
//$role = get_role('editor');
//$role->add_cap('edit_others_pages');
//$role->add_cap('edit_others_posts');
//$role->add_cap('delete_others_pages');
//$role->add_cap('delete_others_posts');
//$role->add_cap('manage_links');
//$role->add_cap('moderate_comments');
 
/* End Editor Restriction  ***************/

Similar Posts:

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">