WordPress.org

Ready to get started?Download WordPress

Codex

Function Reference/add cap

Contents

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

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;

  if ( 'themes.php' == $pagenow && isset( $_GET['activated'] ) ){ // Test if theme is activate
    // Theme is activate
    // 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' ); 
  }
  else {
    // Theme is deactivate
    // Remove the capacity when them is deactivate
    $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 wp-includes/capabilities.php.

Related

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