0

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;
}
0

This function would generate a unique user login slug:

function my_unique_user_slug( $slug ) {
    global $wpdb;

    $check_sql = "SELECT user_login FROM $wpdb->users WHERE user_login = %s LIMIT 1";
    if ( ! $wpdb->get_var( $wpdb->prepare( $check_sql, $slug ) ) ) {
        return $slug;
    }

    $suffix = 2;
    do {
        $alt_slug = $slug . $suffix;
        $user_slug_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_slug ) );
        $suffix++;
    } while ( $user_slug_check );

    return $alt_slug;
}

It is based on the wp_unique_post_slug() function, and you can use it like so:

if ( ! empty( $complete_name ) ) {
    $slug = sanitize_user( preg_replace( '/\s+/u', '', $complete_name ) );
    $new_customer_data['user_login'] = my_unique_user_slug( $slug );
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.