0

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

6
  • This ist not Working. Because the the sales agents is an plugin. It has it own site to register users. Should be something with that: if ( is_user_logged_in() && wcb2bsa_has_role( get_current_user_id(), 'sales_agent' ) ) – d3mi Mar 18 at 11:53
  • I tried everything but im not getting it. maybe someone has that little knowhow to solve this:D – d3mi Mar 25 at 10:51
  • Please use the edit link on your question to add additional information. The Post Answer button should be used only for complete answers to the question. - From Review – Jacob Peattie Mar 25 at 13:01
  • @d3mi I converted your solution into a comment, posting comments as solutions gets you flagged as a spammer and possibly auto-banned – Tom J Nowell Mar 25 at 13:42
  • Also, where did you get $user from? You can't just pull variables out of thin air – Tom J Nowell Mar 25 at 13:43
0

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' );
}
1
  • This does not check if the person creating the user is a sales agent – Tom J Nowell Mar 25 at 13:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.