Wordpress Web Application Development(Third Edition)
上QQ阅读APP看书,第一时间看更新

Creating your first capability

Capabilities are always associated with user roles and hence we cannot create new capabilities without providing a user role. Let's look at the following code for associating custom capabilities with our member user roles created earlier in the Creating application user roles section:

    public function add_application_user_capabilities(){ 
$role = get_role( 'wpwaf_premium_member' );
$role->add_cap( 'follow_forum_activities' );

$role = get_role( 'wpwaf_free_member' );
$role->add_cap( 'follow_forum_activities' );
}

First, we need to retrieve the user role as an object using the get_role function. Then, we can associate new or existing capability using the add_cap function. We need to continue this process for each user role until we assign all the capabilities to the necessary user levels. This function also needs to be executed inside the activation hook. Therefore, we can call this function from the activation_handler function of the WPWAF_Config_Manager class, as shown in the following code:

    public function activation_handler(){
$this->add_application_user_roles();
$this->remove_application_user_roles();
$this->add_application_user_capabilities();
}

Now, we have user role and capabilities related configurations in activation handler of the plugin.