Adding a custom user role with specific capabilities in WordPress
WordPress ships with five built-in roles: Subscriber, Contributor, Author, Editor, and Administrator. For most projects that’s enough, but sometimes you need a role with a very specific set of capabilities — for example, a “Store Manager” who can manage orders but not edit posts, or an “SEO Editor” who can publish but not install plugins.
Problem: How do you add a custom user role in WordPress with exactly the capabilities you need — neither too permissive nor too restrictive?
Solution: Use add_role() on plugin or theme activation. Never call it on every request — it writes to the database each time:
register_activation_hook( __FILE__, 'add_custom_roles' );
function add_custom_roles() {
add_role(
'content_editor',
__( 'Content Editor', 'textdomain' ),
[
'read' => true,
'edit_posts' => true,
'edit_published_posts' => true,
'publish_posts' => true,
'delete_posts' => false,
'upload_files' => true,
'manage_categories' => true,
]
);
}
// Remove the role on plugin deactivation
register_deactivation_hook( __FILE__, function() {
remove_role( 'content_editor' );
} );
To add or remove a capability from an existing role at runtime:
$role = get_role( 'editor' );
$role->add_cap( 'manage_options' ); // grant
$role->remove_cap( 'delete_others_posts' ); // revoke
To assign a role to a user:
$user = new WP_User( $user_id );
$user->set_role( 'content_editor' );
NOTE: Role and capability data is stored in the wp_options table under wp_user_roles. Changes made with add_cap() / remove_cap() are permanent until explicitly reversed — so be deliberate about when and where you call them.