Adding new role to wordpress when plugin activate

To add a new role to WordPress when a plugin is activated, you can use the activate_plugin action hook in your plugin's code. This hook is triggered when a plugin is activated, and you can use it to add a new role to WordPress.

Here's an example of how you can do this:

// In your plugin's code
function add_new_role_on_plugin_activation() {
    // Create a new role
    $role = new WP_Role('new_role_name');
    $role->add_cap('read');
    $role->add_cap('edit_posts');
    // Add the role to the database
    wp_roles()->add_role($role);
}
add_action('activate_plugin', 'add_new_role_on_plugin_activation');

In this example, the add_new_role_on_plugin_activation function is triggered when the plugin is activated. It creates a new role called "new_role_name" and adds two capabilities to it: "read" and "edit_posts". Finally, it adds the role to the database using the wp_roles()->add_role() method.

Note that you need to replace new_role_name with the actual name of the role you want to create.

Also, you can use wp_insert_role function instead of wp_roles()->add_role() to add the role to the database.

wp_insert_role(array(
    'name' => 'new_role_name',
    'capabilities' => array(
        'read' => true,
        'edit_posts' => true,
    ),
));

You can also use add_role function to add the role to the database.

add_role('new_role_name', 'New Role Name', array(
    'read' => true,
    'edit_posts' => true,
));

Make sure to check the documentation of the wp_roles class and the WP_Role class for more information on how to create and manage roles in WordPress.

It's also important to note that you should be careful when creating new roles, as it can affect the security and functionality of your WordPress site. Make sure to test your plugin thoroughly before releasing it to ensure that it doesn't cause any issues.