Set name or shortened emailadress as username when registering through WooCommerce

Viewed 29

WooCommerce has the option: " When creating an account, automatically generate an account username for the customer based on their name, surname or email. "

Currently, it takes the full email address as username. Since it's a membership platform this poses some privacy issues as they can see each other profiles and it shows their 'username' in the URL; mywebsite.com/user/theiremailadress).

How can I use their name+surname or only the beginning of their email? (so nothing after @)

I've already seen a few posts about this topic, like this one, but those are the other way around and not sure how to get this outcome.

Thanks in advance!

1 Answers

Found a solution here that worked for me:

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( str_replace( ' ', '-', $complete_name ) );

    return $new_customer_data;
}
Related