username auto-generated by billing complete name in WooCommerce registration

后端 未结 1 483
心在旅途
心在旅途 2021-01-03 16:53

So I\'ve added various custom fields to the registration page of my WooCommerce webshop as following:

/* ---------------------- Registration page -----------         


        
相关标签:
1条回答
  • 2021-01-03 17:00

    You should eed to use a custom function hooked in woocommerce_new_customer_data filter hook. The code below will replace the wrong and repetitive usernames (that you will set in an array) by the complete billing name:

    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 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) && ! in_array( complete_name, $wrong_user_names ) )
            $new_customer_data['user_login'] = sanitize_user( str_replace( ' ', '-', $complete_name ) );
    
        return $new_customer_data;
    }
    

    Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

    I haven't test this code, but it should work.


    Here is a simpler version that will replace all usernames by the billing complete name.

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

    Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

    I haven't test this code, but it should work.

    0 讨论(0)
提交回复
热议问题