WooCommerce - 在 woocommerce_created_customer 钩子中注册第二个用户

时间:2021-05-13 16:22:17

标签: wordpress woocommerce

当有人通过 WooCommerce 注册为客户后,我在尝试注册第二个用户帐户时遇到问题。我添加了以下 woocommerce_created_customer 钩子:

add_action('woocommerce_created_customer', function($customer_id)
{
    if(isset($_POST['second_user_first_name']) && isset($_POST['second_user_last_name']))
    {
        $createSecondUserId = wp_create_user(strtolower($_POST['second_user_first_name'].'-'.$_POST['second_user_last_name']).'-'.$customer_id, wp_generate_password(), 'test@test.com');

        if(is_wp_error($createSecondUserId))
        {
            $errors = $createSecondUserId->errors;

            print_r($errors);
            die();
        }
    }
});

但是,我在提交新的 WooCommerce 注册时收到以下错误:

Array ( [existing_user_login] => Array ( [0] => Sorry, that username already exists! ) )

很奇怪,因为我在 wp_create_user 函数中设置了一个随机用户名,所以用户名不应该冲突。有人有什么想法吗?

2 个答案:

答案 0 :(得分:0)

您可以使用 username_exists() 来确定给定的用户名是否存在。

add_action( 'woocommerce_created_customer', function($customer_id){

    if( isset( $_POST['second_user_first_name'] ) && isset( $_POST['second_user_last_name'] ) ) {

        if( !username_exists( strtolower( $_POST['second_user_first_name'].'-'.$_POST['second_user_last_name'] ).'-'.$customer_id ) ){

            $createSecondUserId = wp_create_user( strtolower( $_POST['second_user_first_name'].'-'.$_POST['second_user_last_name'] ).'-'.$customer_id, wp_generate_password(), 'test@test.com' );

            if(is_wp_error($createSecondUserId)){

                $errors = $createSecondUserId->errors;
                print_r($errors);
                die();

            }

        }

    }

});

答案 1 :(得分:0)

如果用户名已经存在,您可以通过添加渐进式数字后缀来创建一个新用户名。这样您就可以确保第二个帐户的用户名将始终是唯一的

<块引用>

请注意,如果您使用当前代码运行多个测试,则需要 确保您删除电子邮件地址为 test@test.com 的用户 否则你会得到一个错误:[existing_user_email] => Sorry, that email address is already used!

add_action('woocommerce_created_customer', function( $customer_id ) {
    if ( isset($_POST['second_user_first_name']) && isset($_POST['second_user_last_name']) ) {
        // create the username based on the form data
        $username = strtolower( $_POST['second_user_first_name'] . '-' . $_POST['second_user_last_name'] ) . '-' . $customer_id;
        // if the username already exists it creates a unique one
        if ( username_exists($username) ) {
            $i = 0;
            while ( username_exists($username) ) {
                $username = $username . '-' . ++$i;
            }
        }
        // create the second user
        $createSecondUserId = wp_create_user( $username, wp_generate_password(), 'test@test.com' );
    }
});

代码已经过测试并且可以工作。将它添加到您的活动主题的functions.php。

相关问题