创建用户时以编程方式更新 WooCommerce 用户 [英] Update WooCommerce User programmatically when creating a user

查看:52
本文介绍了创建用户时以编程方式更新 WooCommerce 用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过表单以编程方式创建一个新用户,但我在通过 wp_create_user 获取电话号码和国家/地区设置时遇到问题 - 为什么它不采用这些值?名字和姓氏按预期工作.

Im trying to create a new user programmatically trough a form but Im having problem with getting the phone numer and country set trough wp_create_user - why wont it take the values? First and last name works as expected.

相关代码:

$user_id = wp_create_user( $username, $random_password, $user_email ); 
    wp_update_user([
    'ID' => $user_id,
     'first_name' => rgar( $entry, '20.3' ),
     'last_name'  => rgar( $entry, '20.6' ),
     'phone'      => rgar( $entry, '16' ),
     'country'  => rgar( $entry, '24.6' )
    ]);

推荐答案

在 WooCommerce 中,电话和国家/地区是计费字段,因此正确的用户元键是:

In with WooCommerce the phone and the country are billing fields so the right user meta keys are:

  • billing_country (记住你需要设置一个有效的国家代码)
  • billing_phone

您还需要设置billing_emailbilling_first_namebilling_last_name

因此您的代码将改为,也将您的 wp_create_user() 函数替换为:

So your code is going to be instead, replacing also your wp_create_user() function by:

    $username = rgar( $entry, '20.3' );
    $email    = rgar( $entry, '10' );
    $password = wp_generate_password( 12, false );

    $user_data = array(
        'user_login' => $username,
        'user_pass'  => $password,
        'user_email' => $email,
        'role'       => 'customer',
        'first_name' => rgar( $entry, '20.3' ),
        'last_name'  => rgar( $entry, '20.6' ),
    );

    $user_id  = wp_insert_user( $user_data ); // Create user with specific user data

然后添加 WooCommerce 用户数据有两种方法:

1).使用 WC_Customer 对象和方法:

Then to add the WooCommerce user data there is 2 ways:

1). Using WC_Customer Object and methods:

    $customer = new WC_Customer( $user_id ); // Get an instance of the WC_Customer Object from user Id

    $customer->set_billing_first_name( rgar( $entry, '20.3' ) );
    $customer->set_billing_last_name( rgar( $entry, '20.6' ) );
    $customer->set_billing_country( rgar( $entry, '24.6') );
    $customer->set_billing_phone( rgar( $entry, '16' ) );
    $customer->set_billing_email( $email );

    $customer->save(); // Save data to database (add the user meta data)

2) 或者使用 WordPress update_user_meta() 函数 (老方法):

update_user_meta( $user_id, 'billing_first_name', rgar( $entry, '20.3') );
update_user_meta( $user_id, 'billing_last_name', rgar( $entry, '20.6') );
update_user_meta( $user_id, 'billing_country', rgar( $entry, '24.6') );
update_user_meta( $user_id, 'billing_phone', rgar( $entry, '16') );
update_user_meta( $user_id, 'billing_email', $email );

这篇关于创建用户时以编程方式更新 WooCommerce 用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆