iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Users & Roles

WordPress ships with five built-in roles (Administrator, Editor, Author, Contributor, Subscriber) and a capability system underneath them. You can add custom roles and tweak capabilities per role.

Roles, caps, custom roles

EXAMPLE
// 1) Check what the current user can do
if (current_user_can('publish_posts')) {
    // …
}

if (!current_user_can('edit_post', $post_id)) {
    wp_die('Not allowed.');
}

// 2) Add a custom role at plugin activation
register_activation_hook(__FILE__, function () {
    add_role('shop_manager', 'Shop Manager', [
        'read'              => true,
        'edit_posts'        => true,
        'publish_posts'     => true,
        'edit_products'     => true,    // custom cap from your plugin
        'manage_orders'     => true,
    ]);
});

// 3) Grant or revoke a capability on a role
function add_export_cap() {
    $role = get_role('editor');
    $role->add_cap('export_reports');
}
add_action('admin_init', 'add_export_cap');

// 4) Remove or assign a role to a user
$user = get_user_by('login', 'ada');
$user->set_role('shop_manager');
$user->add_role('editor');           // multiple roles
$user->remove_role('subscriber');

// 5) Map a custom capability for object-level checks
add_filter('map_meta_cap', function ($caps, $cap, $user_id, $args) {
    if ($cap === 'edit_order') {
        $order_id = $args[0];
        if (get_post_field('post_author', $order_id) == $user_id) {
            return ['read'];                 // owner can edit
        }
        return ['manage_orders'];            // others need manage_orders
    }
    return $caps;
}, 10, 4);

Why it matters

Cap checks beat role checks. current_user_can('edit_order', \$id) works with future role changes for free; user_can('administrator') rots the day someone introduces a new role.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
// Roles: Administrator > Editor > Author > Contributor > Subscriber.
Try it Yourself »

Discussion

Loading…