I want to assign a custom user role to customers who register on my website, unless the registration is done via the WooCommerce checkout form.
I have tried several things but nothing targets only the registration form on the login page. I have set up already a custom user role, called "registered_user".
This code works but targets both the registration form on the login page and when a user registers through checkout.
add_filter( 'woocommerce_new_customer_data', 'assign_custom_role' );
function assign_custom_role( $args ) {
$args['role'] = 'registered_user';
return $args;
}
It also adds an additional role, so now users have both "customer" and "registered_user" roles.
I have also tried adding a hidden form field <input type="hidden" name="front_end_reg_form"> to the WooCommerce form_login.php attempting to target the form with:
function add_user_role_frontend_reg( $user_id ) {
if($_POST['front_end_reg_form'] == 'front_end_reg_form')
{
$user = new WP_User( $user_id );
$user->remove_role( 'customer' );
$user->add_role( 'registered_user' );
}
}
add_action('user_register', 'add_user_role_frontend_reg', 10, 1);
Which the above code doesn't do anything. If I change the hook to add_filter( 'woocommerce_new_customer_data', 'add_user_role_frontend_reg' ); I get the error: Cannot create a user with an empty login name.
So I'm stuck. What am I doing wrong and how can I correct it?