Reputation: 33
I've tried to replace username with first name billing using the code below changed from this answer thread, but keep getting 500 error.
If I use first and last name it works but I would prefer to use first name only.
Code is as follows:
add_filter( 'woocommerce_new_customer_data', 'custom_new_customer_data', 10, 1 );
function custom_new_customer_data( $new_customer_data ){
// Complete HERE in this array the wrong usernames you want to replace (coma separated strings)
$wrong_user_names = array( 'info', 'contact' );
// get the first billing name
if(isset($_POST['billing_first_name'])) $first_name = $_POST['billing_first_name'];
if( ( ! empty($first_name) ) ) && in_array( $new_customer_data['user_login'], $wrong_user_names ) ){
// the customer billing complete name
$first_name = $first_name;
// Replacing 'user_login' in the user data array, before data is inserted
$new_customer_data['user_login'] = sanitize_user( str_replace( $first_name ) );
}
return $new_customer_data;
}
My question would be, how would I configure WooCommerce to generate the username by the custom fields: First Name (billing_first_name) instead of full name or username?
Upvotes: 3
Views: 2229
Reputation: 254363
Try the following, to replace username by the billing firstname during checkout registration:
add_filter( 'woocommerce_new_customer_data', 'customer_username_based_on_firstname', 20, 1 );
function customer_username_based_on_firstname( $new_customer_data ){
// Complete HERE in this array the wrong usernames you want to replace (coma separated strings)
$wrong_user_names = array( 'info', 'contact' );
// get the first billing name
if(isset($_POST['billing_first_name'])) $first_name = $_POST['billing_first_name'];
if( ! empty($first_name) && ! in_array( $_POST['billing_first_name'], $wrong_user_names ) ){
// Replacing 'user_login' in the user data array, before data is inserted
$new_customer_data['user_login'] = sanitize_user( $first_name );
}
return $new_customer_data;
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
Your error was coming from
str_replace( $first_name )
. This php function needs 3 arguments.
Upvotes: 3