How to create WordPress custom user role for custom plugin ?
Create custom user role for a WordPress plugin by using WordPress built-in functions.
1. Create the Plugin File : First create a custom plugin if you don’t have one.
1. Create a PHP file for the plugin.
2. Add plugin header:
2. Add Code to Create and Manage the Custom Role :
Create the custom role on plugin activation
1. Define the role and capabilities:
Use `add_role
` to create the custom role when the plugin is activated.
Use `register_activation_hook
` to ensure this function runs when the plugin is activated.
function my_custom_role_plugin_add_role() {
//Define role name and capabilities
$role_name = 'custom_role';
$role_display_name = 'Custom Role';
$capabilities = [
'read' => true,
'edit_posts' => true,
'delete_posts' => false,
// add more capabilities as needed
];
// Add the custom role
add_role($role_name, $role_display_name, $capabilities);
}
//register activation hook to add the role
register_activation_hook(__FILE__, 'my_custom_role_plugin_add_role');
2. Remove the role on deactivation(Optional):
Use `register_deactivation_hook
` to remove the role if needed when the plugin is deactivated.
//Function to remove the custom role
function my_custom_role_plugin_remove_role() {
$role_name = 'custom_role';
remove_role($role_name);
}
//Register deactivation hook to remove the role
register_deactivation_hook(__FILE__, 'my_custom_role_plugin_remove_role');
3. Test Your Plugin: .
Activate the plugin.
Check the new role: Go to users > Add New and check the Role dropdown.
Assign the new role to a user.