Set user role, if an specific role created an user

Im Trying to set an user role. if an specific user role (sales-agents) create an user.

the created user should have the role b2b instead of customer

here is my try:

add_action( 'init', 'b2b_set_user_role' );
    function b2b_set_user_role() { 
   if ( is_user_logged_in()  wcb2bsa_has_role( get_current_user_id(), 'sales_agent' ) ) 
   { 
        $user-remove_role( ‘customer’ );
        $user-add_role( ‘b2b’ );
   }
}

i hope someone can help me

Topic wp-create-user user-roles init Wordpress

Category Web


You can use user_register action, which is invoked after registering a new user.
To add or remove roles/caps, the WP_User class provides methods:

Your code might look like this:

add_action( 'user_register', 'se385135_user_register' );

function se385135_user_register( $user_id )
{
    $user = wp_get_current_user();
    if ( !isset( $user->ID ) || $user->ID == 0 )
        return;
    if ( !in_array( 'sales_agent', $user->roles ) )
        return;

    $created_user = get_user_by( 'ID', $user_id );
    if ( $created_user === false )
        return;

    $created_user->add_role( 'b2b' );
    $created_user->remove_role( 'customer' );
}

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.