Add new role wordpress
To add a new role in WordPress, you can use the add_role
function. Here's an example of how to do it:
function add_new_role() {
$role = 'new_role';
$capabilities = array(
'read' => true,
'edit_posts' => true,
'delete_posts' => true,
'publish_posts' => true,
'edit_published_posts' => true,
'edit_others_posts' => true,
'delete_published_posts' => true,
'delete_others_posts' => true,
'edit_private_posts' => true,
'edit_others_private_posts' => true,
'read_private_posts' => true,
'edit_published_pages' => true,
'edit_private_pages' => true,
'read_private_pages' => true,
'upload_files' => true,
'manage_categories' => true,
'manage_links' => true,
'edit_theme_options' => true,
'moderate_comments' => true,
'manage_options' => true,
);
$role_object = wp_insert_role($role);
if (!is_wp_error($role_object)) {
foreach ($capabilities as $capability => $value) {
add_role_cap($role, $capability, $value);
}
}
}
add_action('admin_init', 'add_new_role');
In this example, we're adding a new role called "new_role" and giving it a set of capabilities. The wp_insert_role
function is used to create the new role, and then we loop through the capabilities array and add each capability to the new role using the add_role_cap
function.
You can adjust the capabilities array to give the new role the permissions you want. For example, if you want the new role to be able to edit posts but not publish them, you would set publish_posts
to false
.
You can also use the add_cap
function to add a capability to a role, like this:
add_cap($role, 'publish_posts', true);
And you can use the remove_cap
function to remove a capability from a role, like this:
remove_cap($role, 'publish_posts');
You can also use the add_role
function to add a new role and set its capabilities in one step, like this:
add_role('new_role', 'New Role', array(
'read' => true,
'edit_posts' => true,
'delete_posts' => true,
'publish_posts' => true,
//...
));
This is a more concise way to add a new role and set its capabilities, but it's less flexible than using the wp_insert_role
and add_role_cap
functions separately.