Skip to content
Advertisement

Automatically generate username based on user ID in WooCommerce

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?

img

Example: User ID = 101, Auto generated Username = 101

Is it possible?

Any help would really be appreciated. Thanks!

Advertisement

Answer

First of all, make sure that the following option is checked via the WooCommerce settings

enter image description here


Normally than you could use the woocommerce_new_customer_username filter hook to change the generated username.

Copied from includes/wc-user-functions.php

JavaScript

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)

JavaScript

And

  • wpdb – WordPress database access abstraction class.

  • update_user_meta() – Update user meta field based on user ID.


So you get:

JavaScript

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.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement