Creating a Custom User Role
Custom Code Solution
Here's a code snippet to add in your theme's functions.php
file or in a site-specific plugin. This code creates a new user role with specific capabilities:
This code creates a new "Content Editor Plus" role with custom permissions:
function add_custom_user_role() {
add_role(
'content_editor_plus',
'Content Editor Plus',
array(
'read' => true,
'edit_posts' => true,
'edit_published_posts' => true,
'publish_posts' => true,
'edit_pages' => true,
'edit_published_pages' => true,
'publish_pages' => true,
'upload_files' => true,
'moderate_comments' => true
)
);
}
add_action('init', 'add_custom_user_role');
To remove the role if needed:
function remove_custom_user_role() {
remove_role('content_editor_plus');
}
// Uncomment next line to remove the role
// add_action('init', 'remove_custom_user_role');
To add extra capabilities to an existing role:
function add_role_capabilities() {
$role = get_role('content_editor_plus');
$role->add_cap('edit_others_posts');
$role->add_cap('edit_others_pages');
}
add_action('init', 'add_role_capabilities');
Important Notes:
- Run this code once to create the role
- After role creation, you can comment out or remove the code
- Role persists in the database even after code removal
- New users can be assigned this role from the WordPress admin panel
Plugin Alternative
If you prefer a plugin solution, these options are reliable:
Best Practices:
- Store role creation code in a site-specific plugin instead of theme's functions.php
- Use specific capability names from WordPress Codex
- Test role permissions thoroughly before deployment
- Consider using a plugin for complex role management needs