Languages: English • 日本語 (Add your language)
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
<?php
or
global $wp_roles; // global class wp-includes/capabilities.php
$wp_roles->add_cap( $role, $cap );
?>
<?php
$role = get_role( 'author' );
$role->add_cap( $cap );
?>
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' );
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();
.
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