2

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

相关代码:

$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' )
    ]);
4

2 回答 2

2

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

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

您还需要设置billing_email,billing_first_namebilling_last_name

因此,您的代码将改为通过以下方式替换您的wp_create_user()函数:

    $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对象和方法:

    $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)或使用WordPressupdate_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 );
于 2020-11-03T21:02:46.740 回答
0

您可以添加countryphone作为用户元并将其保存在用户元表中:

add_user_meta( $user_id, 'country', rgar( $entry, '24.6'));
add_user_meta( $user_id, 'phone', rgar( $entry, '16'));

WordPress 法典:点击这里

于 2020-11-03T15:55:48.353 回答