admin管理员组

文章数量:1300054

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

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

Share Improve this question asked Mar 16, 2021 at 8:04 d3mid3mi 132 bronze badges 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 Commented Mar 18, 2021 at 11:53
  • I tried everything but im not getting it. maybe someone has that little knowhow to solve this:D – d3mi Commented Mar 25, 2021 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 Commented Mar 25, 2021 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 Commented Mar 25, 2021 at 13:42
  • Also, where did you get $user from? You can't just pull variables out of thin air – Tom J Nowell Commented Mar 25, 2021 at 13:43
 |  Show 1 more comment

1 Answer 1

Reset to default 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:

  • add_cap(), add_role()
  • remove_cap(), remove_role()

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' );
}

本文标签: initSet user roleif an specific role created an user