Created
April 5, 2024 06:52
-
-
Save pramodjodhani/15ff262e5d352e0a1e25ee352690115d to your computer and use it in GitHub Desktop.
WooCommerce change new customer's auto generated username format.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Custom new username for new customer. | |
* | |
* @param string $username Username. | |
* @param string $email Email. | |
* @param array $new_user_args New user args. | |
* @param string $suffix Suffix. | |
* | |
* @return string | |
*/ | |
function custom_new_customer_username( $username, $email, $new_user_args, $suffix ) { | |
$billing_first_name = isset( $new_user_args['first_name'] ) ? $new_user_args['first_name'] : ''; | |
$billing_last_name = isset( $new_user_args['last_name'] ) ? $new_user_args['last_name'] : ''; | |
$new_username = sanitize_user( strtolower( $billing_first_name . '.' . $billing_last_name ) ); | |
if ( username_exists( $new_username ) ) { | |
return append_random_number( $new_username ); | |
} | |
return $new_username; | |
} | |
add_filter( 'woocommerce_new_customer_username', 'custom_new_customer_username', 10, 4 ); | |
/** | |
* Append random number to username if it already exists. | |
* | |
* @param string $username Username. | |
* | |
* @return string | |
*/ | |
function append_random_number( $username ) { | |
$random_number = wp_rand( 1, 999 ); | |
$new_username = $username . $random_number; | |
if ( username_exists( $new_username ) ) { | |
return append_random_number( $username ); | |
} | |
return $new_username; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment