WordPress插件 - 在WooCommerce中存储送货地址


WordPress plugin - Store shipping address in WooCommerce

我正在尝试将送货地址添加到当前客户,但我不起作用。

这是我的代码:

$userdata = array(
    'user_login'    =>   $email,
    'user_email'    =>   $email,
    'user_pass'     =>   $password,
    'first_name'    =>   $first_name,
    'last_name'     =>   $last_name
);
$user = wp_insert_user( $userdata ); // User successfully inserted
$customer             = new WC_Customer();
$customer->set_shipping_city("Bangalore"); //Doesn't work
global $woocommerce;
$woocommerce->customer->set_shipping_city("Bangalore"); //Doesn't work

我做错了什么?

我认为

问题是$user = wp_insert_user( $userdata );不会插入任何数据,而只是将其存储在变量$user然后在代码中不再使用它。
然后set_shipping_city();还有一个会话数据功能,您需要使用现有的客户或购物车会话(WC_cart)。

所以我稍微改变了你的代码:

$userdata = array (
    'user_login'    =>  $email,
    'user_email'    =>  $email,
    'user_pass'     =>  $password,
    'first_name'    =>  $first_name,
    'last_name'     =>  $last_name
) ;
$user_id = wp_insert_user( $userdata ) ;
// Here you insert your user data with a 'customer' user role
wp_update_user( array ('ID' => $user_id, 'role' => 'customer') ) ;
//Once customer user is inserted/created, you can retrieve his ID
global $current_user;
$user = wp_get_current_user();
$user_id = $user->ID;
// or use instead:  $user_id = get_current_user_id();
// Checking if user Id exist
if( !empty( $user_id ) ) {
    // You will need also to add this billing meta data
    update_user_meta( $user_id, 'billing_first_name', $first_name );
    update_user_meta( $user_id, 'billing_last_name', $last_name );
    update_user_meta( $user_id, 'billing_email', $email );
    // optionally shipping meta data, that could be different
    update_user_meta( $user_id, 'shipping_first_name', $first_name );
    update_user_meta( $user_id, 'shipping_last_name', $last_name );
    update_user_meta( $user_id, 'shipping_email', $email );
    // Now you can insert the required billing and shipping city
    update_user_meta( $user_id, 'billing_city', 'Bangalore' );
    // optionally shipping_city can be different…
    update_user_meta( $user_id, 'shipping_city', 'Bangalore' );
} else {
    // echo 'User Id doesn't exist';
}

然后您可以使用update_user_meta()函数插入任何地址数据,keys

billing_first_name
billing_last_name
billing_company
billing_email
billing_phone
billing_address_1
billing_address_2
billing_country
billing_state
billing_postcode
shipping_first_name
shipping_last_name
shipping_company
shipping_email
shipping_phone
shipping_address_1
shipping_address_2
shipping_country
shipping_state
shipping_postcode

参考:

  • WordPress Development StackExchange - wp_insert_user角色不起作用
  • WordPress函数update_user_meta()
  • WordPress函数wp_insert_user()
  • WordPress 函数 wp_update_user()
  • WordPress函数wp_get_current_user()
  • WordPress函数get_current_user_id()
您可以使用

wp_update_user( $userdata )

其中$userdata是字段列表。

使用wp_update_user您可以更新字段