WordPress.org

Codex

Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

Function Reference/add cap

Description

Adds a capability to a role or specific user. Changing the capabilities of a role or user is persistent, meaning the added capability will stay in effect until explicitly revoked.

N.B.: This setting is saved to the database (in table wp_options, field wp_user_roles), so it might be better to run this on theme/plugin activation

Usage

<?php 
  
global $wp_roles// global class wp-includes/capabilities.php
  
$wp_roles->add_cap$role$cap ); 
?> 
or <?php
  $role 
get_role'author' );
  
$role->add_cap$cap );
?> 

Parameters

role (just with WP_Roles)
(string) (Required) role name
Default: None
cap
(string) (Required) capability name
Default: None
grant
(boolean) (optional) Whether the role is capable of performing this capability.
Default: true

Return Values

void 
No return value

Example

function add_theme_caps() {
    // gets the author role
    $role = get_role( 'author' );

    // This only works, because it accesses the class instance.
    // would allow the author to edit others' posts for current theme only
    $role->add_cap( 'edit_others_posts' ); 
}
add_action( 'admin_init', 'add_theme_caps');

NB: This setting is saved to the database, so it might be better to run this on theme/plugin activation

function add_theme_caps(){
  global $pagenow;

  // gets the author role
  $role = get_role( 'author' );

  if ( 'themes.php' == $pagenow && isset( $_GET['activated'] ) ){ // Test if theme is activated
    // Theme is activated

    // This only works, because it accesses the class instance.
    // would allow the author to edit others' posts for current theme only
    $role->add_cap( 'edit_others_posts' ); 
  }
  else {
    // Theme is deactivated
    // Remove the capability when theme is deactivated
    $role->remove_cap( 'edit_others_posts' ); 
  }
}
add_action( 'load-themes.php', 'add_theme_caps' );

To add capability to specific user :

$user = new WP_User( $user_id );
$user->add_cap( 'can_edit_posts' );

Notes

There is no public function called add_cap() - just the class methods inside WP_Roles, WP_Role, WP_User that can add capabilities.

If you want to add a new role with capabilities, just add them when you add the role using add_role();.

Changelog

Source File

add_cap is located in three places:

wp-includes/class-wp-role.php, wp-includes/class-wp-roles.php, wp-includes/class-wp-user.php

Related

Roles and Capabilities:
See also index of Function Reference and index of Template Tags.