Skip to content
Tutorials Center
My learning

Topics

Lesson 54 of 68 ยท Forms, Security and Data Handling

Users, Roles and Capabilities

Learn how WordPress roles map to capabilities, how current_user_can and meta capabilities decide access, and how to add roles safely in a plugin.

Every privileged thing in WordPress, from publishing a post to installing a plugin, is guarded by a question: "is this user allowed to do that?" WordPress answers it with capabilities. A capability is a single permission string such as edit_posts or manage_options. A role is only a named bundle of capabilities, such as Editor or Subscriber.

This lesson explains how the two relate, how current_user_can() decides, why some capabilities depend on the object you are acting on (meta capabilities), and how a plugin can add its own roles. You already know nonces from Forms and Nonces: a nonce proves a request was intended, while a capability check proves the user is allowed. You need both.

Real WordPress code below is read-only. The runnable examples are plain-PHP stand-ins that follow the same rules, so you can see the logic without a WordPress install.

Roles are bundles, capabilities are the rule

A default WordPress install ships five roles (a multisite network adds a sixth, Super Admin, covered in Multisite Overview):

Role Typical purpose
Subscriber Can read and manage their own profile
Contributor Writes posts but cannot publish them
Author Publishes and manages their own posts, uploads files
Editor Manages all posts, pages, comments and categories
Administrator Manages the whole site: settings, themes, plugins, users

The code never asks "is this user an Editor?". It asks for the capability that the action needs. That way a site owner can change what Editors may do without any plugin breaking, and a custom role works everywhere automatically.

PHP
// Good: ask about the permission, not the role.
if ( current_user_can( 'manage_options' ) ) {
    // show the settings screen
}

// Fragile: breaks for custom roles and multi-role users.
$user = wp_get_current_user();
if ( in_array( 'administrator', $user->roles, true ) ) {
    // avoid this
}

Roles live in a single option, user_roles, as a serialized array of role names to capability lists. A user's own roles are stored in user meta under capabilities (for example a:1:{s:6:"editor";b:1;}). A user can hold several roles, and the user meta can also carry single capabilities granted directly to that user. The effective set is the union.

flowchart LR
    U["User<br/>(usermeta: capabilities)"] --> R1["Role: editor"]
    U --> X["Extra capability<br/>granted to this user"]
    R1 --> C1["edit_posts"]
    R1 --> C2["edit_others_posts"]
    R1 --> C3["publish_posts"]
    X --> C4["upload_files"]
    C1 --> D{"current_user_can(<br/>'edit_posts')"}
    C4 --> D

A user's effective capabilities are the union of their roles' capabilities and any capabilities assigned directly.

Checking capabilities

current_user_can( $capability, ...$args ) checks the logged-in user. user_can( $user, $capability ) checks any user, and $role->has_cap() checks a role object. A guest has no capabilities at all, so every check returns false.

The golden rule: check on every privileged action, on the server, right before doing the work. Hiding a menu item is cosmetic. An attacker never needs your menu to send a request.

PHP
add_action( 'admin_post_myplugin_export', 'myplugin_handle_export' );

function myplugin_handle_export(): void {
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_die( esc_html__( 'You are not allowed to do this.', 'myplugin' ), 403 );
    }

    check_admin_referer( 'myplugin_export' ); // the nonce check

    // ... do the privileged work ...
}

Choose the narrowest capability that fits. manage_options means "can change site settings", which is almost always an Administrator. If your plugin lets editors curate a list, edit_others_posts is more honest than manage_options.

The next stand-in builds a role table from inheritance, grants one user an extra capability, and prints a matrix. Real WordPress stores roles in the database and checks them through WP_Role and WP_User, but the union rule is the same.

PHP Role and capability matrix with can()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Read the second table row by row: cy is only a Subscriber, yet can upload files because that capability was granted to the user directly, and dee gets the union of two roles. eve has no role, which is what a logged-out visitor looks like.

Meta capabilities: it depends on the object

Some questions cannot be answered by a single flat permission. "Can this user edit post 42?" depends on who wrote post 42, whether it is published, and its post type. WordPress calls capabilities like edit_post, delete_post, read_post and edit_user meta capabilities. You pass the object ID as an extra argument:

PHP
if ( current_user_can( 'edit_post', $post_id ) ) {
    // allowed to edit this specific post
}

Internally, map_meta_cap() translates the meta capability into the primitive capabilities that the user must have. For edit_post on a post the user wrote, that is roughly edit_posts (plus edit_published_posts if it is already published). For someone else's post it is edit_others_posts. The user needs all of the mapped primitives.

Plugins can influence this mapping with the map_meta_cap filter, and can add or remove individual capabilities for one check with the user_has_cap filter. Both are powerful: a bug there changes security for the whole site, so keep such filters small and test them.

The stand-in below mirrors the shape of that translation for posts. It is a simplified version, not the full core logic (core also handles post types, private posts and a few edge cases).

PHP map_meta_cap: from edit_post to primitive capabilities

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Notice that the same user gets different answers for different posts. This is why a bare current_user_can( 'edit_posts' ) is not enough before editing a specific post: it only says the user can edit posts in general, not that they can edit this one.

Creating roles and capabilities

A plugin that needs its own permissions adds them with add_role() and the WP_Role methods. Because roles are stored in the database, do this once on activation, not on every request. Adding capabilities on every init does needless writes and can quietly revert a site owner's changes.

PHP
register_activation_hook( __FILE__, 'myplugin_activate' );

function myplugin_activate(): void {
    add_role(
        'event_manager',
        __( 'Event Manager', 'myplugin' ),
        array(
            'read'                 => true,
            'edit_events'          => true,
            'edit_others_events'   => true,
            'publish_events'       => true,
        )
    );

    // Give administrators the same powers.
    $admin = get_role( 'administrator' );
    if ( $admin ) {
        $admin->add_cap( 'edit_events' );
        $admin->add_cap( 'edit_others_events' );
        $admin->add_cap( 'publish_events' );
    }
}

register_uninstall_hook( __FILE__, 'myplugin_uninstall' );

function myplugin_uninstall(): void {
    remove_role( 'event_manager' );
    $admin = get_role( 'administrator' );
    if ( $admin ) {
        $admin->remove_cap( 'edit_events' );
        $admin->remove_cap( 'edit_others_events' );
        $admin->remove_cap( 'publish_events' );
    }
}

Custom post types use these names when you set capability_type and map_meta_cap (see Custom Post Types). Remember the cleanup half: roles and capabilities you add stay in the database after deactivation, so remove them at uninstall as shown in Activation, Deactivation and Uninstall.

Users, user meta and the login flow

Users live in wp_users (login, hashed password, email) and wp_usermeta (everything else: roles, first name, preferences). Your plugin can store per-user data with get_user_meta(), update_user_meta() and delete_user_meta(). They work like post meta from Custom Fields and Post Meta, keyed by user ID. Never store secrets in plain text there.

At a high level, logging in works like this:

  1. The visitor submits wp-login.php with a username and password.
  2. wp_signon() calls wp_authenticate(), which runs the authenticate filters. Core checks the password hash; plugins (two-factor, rate limiting, SSO) can add their own checks here.
  3. On success, wp_set_auth_cookie() sends an authentication cookie. WordPress also sets a wordpress_logged_in_ cookie that identifies the session on the front end.
  4. On later requests, core reads those cookies early in the bootstrap (see How WordPress Handles a Request), validates them, and sets the current user. That is why current_user_can() works from init onwards.
sequenceDiagram
    participant B as Browser
    participant L as wp-login.php
    participant A as authenticate filters
    B->>L: POST username and password
    L->>A: wp_authenticate()
    A-->>L: WP_User or WP_Error
    L-->>B: Set auth cookies and redirect
    B->>L: Later request with cookies
    L-->>B: current user is set, capabilities apply

Authentication proves who the user is; capabilities then decide what that user may do.

Never trust a user ID or role that arrives in a request. Always derive the acting user from the cookie session (get_current_user_id()), and when you do need to act on another user's data, check a capability such as edit_user against that target ID.

Common mistakes

  • Checking is_admin() as if it were a permission check. It only tells you whether the request is for an admin screen, and requests to admin-ajax.php count as admin screens even when the visitor is logged out.
  • Checking a role name instead of a capability.
  • Forgetting the capability check in AJAX, REST and admin-post.php handlers, because "only my page calls it".
  • Using manage_options for everything. It works, but it hides your plugin from every role that could legitimately use it.
  • Granting capabilities on every page load instead of on activation.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is a role in WordPress?

    A capability is one permission; a role is a named set of them. Code should ask about capabilities so that custom roles and changed role settings keep working.
  2. 2. A user wrote a published post. Which check is the right one before letting them edit that specific post?

    edit_post is a meta capability. WordPress maps it to the primitive capabilities needed for that particular post, such as edit_others_posts or edit_published_posts, depending on authorship and status.
  3. 3. When should a plugin call add_role() for its custom role?

    Roles are stored in the database, so they persist. Adding them once on activation avoids repeated writes and avoids overwriting changes that a site owner made later.
  4. 4. Why is hiding a menu item not enough to protect an action?

    A menu is just a convenience for the UI. The request handler must verify the capability on the server every time, in addition to checking a nonce.

Summary

  • Capabilities are single permissions; roles are named bundles of them; a user's effective set is the union of their roles and directly granted capabilities.
  • Ask current_user_can() about capabilities, never about role names, and check on every privileged action on the server.
  • Meta capabilities such as edit_post take an object ID and are mapped to primitive capabilities by map_meta_cap().
  • Add roles and capabilities once on activation and remove them on uninstall.
  • Authentication (cookies) says who the user is; capabilities say what they may do; nonces say the request was intended.

Next, put these ideas together in a wider checklist: Hardening and Securing a WordPress Site.