Implementation of role and permission control in wordpress
1. Configuration of WordPress system roles and permissions
This configuration is stored in the wp_options table.
It can be obtained in the following ways:
$roles= new WP_Roles();
or
get_option(wp_user_roles);
2. role and cap
Role is the role and cap is the ability.
A character has multiple abilities. When a user becomes this role, the configuration of the role and corresponding capabilities will be written to the user's meta data (wp_usermetas table).
There will be relevant data in the User object.
Use $user->roles to get relevant role data.
Use $user->allcaps to get related capabilities.
3. Three functions
set_role()
Setting the user's role will delete all the user's previous roles and set a new role.
remove_role()
Two usages:
remove_role(role1): Indicates removing role1 from the system role configuration (wp_option).
$user->remove_role(role1): Indicates that role1 is removed from all roles of the user.
add_role()
There are also two usages.
add_role(role1): Indicates adding role1 to the system role configuration (wp_option).
$user->add_role(role1): means adding role role1 to the user, but it will not affect the user's existing roles.
4. Judgment authority
By judging the user role
Achieved through judgment ability
5. Best practices for plug-in role systems
You can refer to bbpress.
WordPress has existing roles as a “role family”.
Plug in your own character as another "character family".
Each user can only have one character series.
The implementation of the plug-in's role system (storage, configuration, permission judgment) is the same as that of WordPress.