我有一个功能,可以在购买后将用户创建为woocommerce_thankyou
。用户已创建,但我也尝试设置usermeta字段,似乎被忽略。这是功能:
function wc_register_user_post_purchase( $order_id ) {
// Get the order data
$order = new WC_Order( $order_id );
// Get the email address from the order
$order_email = $order->billing_email;
// Check to see if there is already a user with the order email
$acct_username = username_exists( $order_email );
$acct_email = email_exists( $order_email );
// If the user doesn't exist, create an account
if ( $acct_username == false && $acct_email == false ) {
// Generate a password
$random_password = wp_generate_password();
// Create a new user
$created_user_id = wp_create_user( $order_email, $random_password, $order_email );
// Set an 'acct_auto_created' custom field so we can check it later
update_user_meta( $created_user_id, 'acct_auto_created', 'auto_generated_pass' );
}
}
add_action( 'woocommerce_thankyou', 'wc_register_user_post_purchase', 10, 1 );
如果我在db中查看创建的用户ID的wp_usermeta表,则acct_auto_created字段根本不会被设置。
我在这里缺少什么?
谢谢!
答案 0 :(得分:0)
尝试从$ order_id获取user_id,如
$order = new WC_Order( $order_id );
$user_id = $order->user_id;
if($user_id){
update_user_meta( $user_id, 'acct_auto_created', 'auto_generated_pass' );
}
或
$user_id = wp_insert_user(
array(
'user_login' => $order_email,
'user_pass' => $random_password,
'user_email' => $order_email,
)
);
update_user_meta( $user_id, 'acct_auto_created', 'auto_generated_pass' );
或
if( null == username_exists( $order_email ) ) {
// Generate the password and create the user
$password = wp_generate_password( 12, false );
$user_id = wp_create_user( $order_email, $password, $order_email );
// Set the nickname
wp_update_user(
array(
'ID' => $user_id,
'nickname' => $order_email
)
);
// Set the role
$user = new WP_User( $user_id );
$created_user_id = $user->ID;
update_user_meta( $created_user_id, 'acct_auto_created', 'auto_generated_pass' );
}