WordPress User Capabilities
User capabilities in WordPress are fine-grained permissions that define what a user can or cannot do within the system. Each role in WordPress (Administrator, Editor, Author, Contributor, Subscriber, or custom roles) is essentially a collection of capabilities. Capabilities govern actions such as editing posts, managing plugins, moderating comments, or accessing the WordPress REST API. Developers can also create custom capabilities to secure plugin functionality or restrict access to specific features.
How it works
- Capabilities are mapped to roles and stored in the database.
- WordPress provides core functions to check and enforce them:
current_user_can( 'edit_posts' )
→ checks if the current user can perform the action.user_can( $user_id, 'delete_users' )
→ checks capability for a specific user.map_meta_cap()
→ maps meta capabilities (likeedit_post
) to primitive ones (likeedit_posts
).
- Plugins and themes can add or remove capabilities from roles with:
$role->add_cap( 'custom_capability' );
$role->remove_cap( 'edit_users' );
Why it matters
Capabilities are the foundation of WordPress’s security model. They ensure users only access features appropriate for their role. Without proper capability checks, plugins or themes could expose sensitive actions to unauthorized users, leading to privilege escalation and site compromise.
Examples
Checking a capability before running code:
if ( current_user_can( 'manage_options' ) ) {
// Show admin-only settings
}
Adding a custom capability to the Editor role:
function myplugin_add_capability() {
$role = get_role( 'editor' );
if ( $role ) {
$role->add_cap( 'manage_events' );
}
}
add_action( 'init', 'myplugin_add_capability' );
Restricting REST API endpoints:
register_rest_route( 'myplugin/v1', '/data', [
'methods' => 'GET',
'callback' => 'myplugin_get_data',
'permission_callback' => function() {
return current_user_can( 'manage_options' );
}
]);