// Add Username Field to Registration Form
add_action( 'woocommerce_register_form_start', 'custom_woocommerce_register_username' );
function custom_woocommerce_register_username() {
?>
<p class="form-row form-row-wide">
<label for="reg_username"><?php _e( 'Username', 'woocommerce' ); ?> <span class="required">*</span></label>
<input type="text" class="input-text" name="username" id="reg_username" value="<?php echo ( ! empty( $_POST['username'] ) ) ? esc_attr( wp_unslash( $_POST['username'] ) ) : ''; ?>" />
</p>
<?php
}
// Validate Username Field
add_filter( 'woocommerce_registration_errors', 'custom_woocommerce_registration_errors_username', 10, 3 );
function custom_woocommerce_registration_errors_username( $errors, $username, $email ) {
if ( empty( $_POST['username'] ) ) {
$errors->add( 'username_error', __( 'Username is required!', 'woocommerce' ) );
} elseif ( username_exists( $_POST['username'] ) ) {
$errors->add( 'username_error', __( 'This username is already taken. Please choose another one.', 'woocommerce' ) );
}
return $errors;
}
// Save Username Field
add_action( 'woocommerce_created_customer', 'custom_save_registration_fields_username' );
function custom_save_registration_fields_username( $customer_id ) {
if ( isset( $_POST['username'] ) && ! empty( $_POST['username'] ) ) {
wp_update_user( array(
'ID' => $customer_id,
'user_login' => sanitize_user( $_POST['username'] ),
) );
}
}
// Prevent Auto-Generation of Username from Email
add_filter( 'woocommerce_new_customer_data', 'custom_override_auto_generated_username', 10, 1 );
function custom_override_auto_generated_username( $data ) {
if ( isset( $_POST['username'] ) && ! empty( $_POST['username'] ) ) {
$data['user_login'] = sanitize_user( $_POST['username'] );
}
return $data;
}