W
W
webga2018-09-25 09:49:49
WordPress
webga, 2018-09-25 09:49:49

How to update the user's role by condition at the time of registration?

Please tell the wordpress amateur how to update the user role depending on the meta data passed at the time of registration.
I wrote this code but it doesn't work.

add_action( 'user_register', 'my_user_registration' );
function my_user_registration( $user_id ) {
  $meta_com = get_user_meta( $user_id, 'user_type', true );
  $value_yes = 'yes';
  $role_yes = 'company';
  $role_no = 'customer';
  if ( $meta_com == $value_yes) {
    wp_update_user( array( 'ID' => $user_id, 'role' => $role_yes ) );
  } else {
    wp_update_user( array( 'ID' => $user_id, 'role' => $role_no ) );
}
}

The essence of the problem: It is necessary that during registration the woocommerce client be assigned a role depending on the value of $type_user passed, the data is written to the database checked! Can be implemented without checks. the user type field is implemented as select and there will always be some value.
type_user can only take the values ​​yes or no.
Tried the same through set_role, remove_role, add_role, nothing happens.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Igor Mavlikhanov, 2018-09-25
@Gori4ka

Try like this:

add_action('user_register', 'my_user_registration');
function my_user_registration($user_id)
{
    $meta_com  = get_user_meta($user_id, 'user_type', true);
    $user      = new WP_User($user_id);
    $value_yes = 'yes';
    $role_yes  = 'company';
    $role_no   = 'customer';
    if ($meta_com == $value_yes) {
        $user->add_role($role_yes);
    } else {
        $user->add_role($role_no);
    }
}

W
webga, 2018-09-26
@webga

Already found a solution!

add_action( 'woocommerce_created_customer', 'my_user_registration' );
function my_user_registration( $user_id ) {

  $meta_com = get_user_meta( $user_id, 'user_type', true );
  $value_yes = 'yes';
  $role_yes = 'company';
  $role_no = 'customer';
  if ( $meta_com == $value_yes) {
    wp_update_user( array( 'ID' => $user_id, 'role' => $role_yes ) );
  } else {
    wp_update_user( array( 'ID' => $user_id, 'role' => $role_no ) );

}
}

It fires before the user_type meta is written to the database, and this was the problem.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question