I’m working on a WooCommerce project where each user have an ID number. I would like to use the default WooCommerce username field for this user ID.
When creating an account, can I automatically generate an account username for the customer based on their user ID?
Example:
User ID = 101,
Auto generated Username = 101
Is it possible?
Any help would really be appreciated. Thanks!
2
Answers
Option 1
You can edit the
wp_insert_user
function that creates the user and change parameters. This function requires an array (or object) of user data to create the user so you just add whatever you want touser_login
. All parameters and examples here.Option 2
If you can’t edit the
wp_insert_user
function you can always call a custom SQL query to updateuser_login
:Ideally use a hook/action just after user registration.
First of all, make sure that the following option is checked via the WooCommerce settings
Normally than you could use the
woocommerce_new_customer_username
filter hook to change the generated username.Copied from includes/wc-user-functions.php
However, you want to determine the
$username
based on the$user_id
,but the
$user_id
is determined after data such as username, email address, etc. has been added via wp_insert_user()So the solution is to update the
$username
based on the$user_id
immediately after a user is registered, and this can be done via:Copied from wp-includes/user.php (WordPress)
And
wpdb – WordPress database access abstraction class.
update_user_meta() – Update user meta field based on user ID.
So you get:
Note: Know that a customer/user can change some of these adjustments via his profile (my account), if you do not want this, you will have to make additional adjustments.