I have a public-viewed community site. I am able to insert First & Last Name fields in WooCommerce Registration form, and auto-generate username based on the combination of First+Last Name.
But if there are two persons with the same First & Last Name, the registration will fail because of username exists if one person has registered earlier.
Can you help me with auto-generating numbers after the username if the username exists? For example, first person is John Doe, his username will be johndoe. So, if the second person with the same name registered, I want it to be, like, johndoe1. If there is third person with the same name registered, that would be johndoe2.
Thank you in advance!
Here's my code for that auto generate username:
add_filter( 'woocommerce_new_customer_data', 'custom_new_customer_data', 10, 1 );
function custom_new_customer_data( $new_customer_data ){
// get the first and last billing names
if(isset($_POST['billing_first_name'])) $first_name = $_POST['billing_first_name'];
if(isset($_POST['billing_last_name'])) $last_name = $_POST['billing_last_name'];
// the customer billing complete name
if( ! empty($first_name) || ! empty($last_name) )
$complete_name = $first_name . ' ' . $last_name;
// Replacing 'user_login' in the user data array, before data is inserted
if( ! empty($complete_name) )
$new_customer_data['user_login'] = sanitize_user( preg_replace('/\s+/u', '', $complete_name) );
return $new_customer_data;
}