在Woocommerce结帐注册中通过结算名字替换用户名

时间:2018-06-16 22:35:49

标签: php wordpress woocommerce registration account

我尝试使用changed from this answer thread下面的代码替换使用名字结算的用户名,但仍然会收到500错误。

如果我使用名字和姓氏,它可以使用,但我更喜欢使用名字。

代码如下:

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

我的问题是,如何配置WooCommerce以通过自定义字段生成用户名:名字(billing_first_name)而不是全名或用户名?

1 个答案:

答案 0 :(得分:2)

请尝试以下操作,在结帐注册时使用结算名称替换用户名:

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

代码放在活动子主题(或活动主题)的function.php文件中。经过测试和工作。

  

您的错误来自str_replace( $first_name )。这个php函数需要3个参数。