WP_Role::add_cap( string $cap, bool $grant = true )

Assign role a capability.

Parameters

$capstringrequired
Capability name.
$grantbooloptional
Whether role has capability privilege.

Default:true

More Information

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

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.

Source

public function add_cap( $cap, $grant = true ) {
	$this->capabilities[ $cap ] = $grant;
	wp_roles()->add_cap( $this->name, $cap, $grant );
}

Changelog

VersionDescription
2.0.0Introduced.

User Contributed Notes

  1. Skip to note 3 content

    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 active
    		 // Theme is active
    		 // 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 deactivated
    		 // Remove the capacity when theme 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' );

You must log in before being able to contribute a note or feedback.