但是,据我所知,这只会在用户更新自己的个人资料时启动。
是的,没错。
在创建用户帐户时运行它并没有产生我想要的结果。
创建/注册用户时应使用的挂钩是user_register.
所以你可以用这个,把两者都勾起来profile_update 和user_register:
// Note that you should use add_action() and not add_filter()
add_action( \'profile_update\', \'custom_update_checkout_fields\' );
add_action( \'user_register\', \'custom_update_checkout_fields\' );
自从第二次钩拳之后(
user_register) 仅提供一个参数,然后省略
$old_user_data 从功能;其次,你应该使用
get_userdata()而不是
wp_get_current_user() 获取正在更新或创建的用户。
我使用的完整代码:
add_action( \'profile_update\', \'custom_update_checkout_fields\' ); // Fires immediately after an existing user is updated.
add_action( \'user_register\', \'custom_update_checkout_fields\' ); // Fires immediately after a new user is registered.
function custom_update_checkout_fields( $user_id ) {
$current_user = get_userdata( $user_id ); // Here we use get_userdata() and not wp_get_current_user().
// Updating Billing info
if ( $current_user->user_firstname != $current_user->billing_first_name )
update_user_meta( $user_id, \'billing_first_name\', $current_user->user_firstname );
if ( $current_user->user_lastname != $current_user->billing_last_name )
update_user_meta( $user_id, \'billing_last_name\', $current_user->user_lastname );
if ( $current_user->user_email != $current_user->billing_email )
update_user_meta( $user_id, \'billing_email\', $current_user->user_email );
// Updating Shipping info
if ( $current_user->user_firstname != $current_user->shipping_first_name )
update_user_meta( $user_id, \'shipping_first_name\', $current_user->user_firstname );
if ( $current_user->user_lastname != $current_user->shipping_last_name )
update_user_meta( $user_id, \'shipping_last_name\', $current_user->user_lastname );
if ( $current_user->user_email != $current_user->shipping_email )
update_user_meta( $user_id, \'shipping_email\', $current_user->user_email );
}
但请注意
user_register 如果客户是匿名的,并且不允许创建WordPress/用户帐户,则不会调用hook。
其他代码可以使用woocommerce_checkout_get_value 钩子来自动填充表单数据,不过如果元数据存在,WooCommerce实际上会自动填充。
add_filter( \'woocommerce_checkout_get_value\', \'custom_autofill_customer_data\', 10, 2 );
function custom_autofill_customer_data( $value, $input ) {
$current_user = wp_get_current_user();
if ( $current_user ) {
switch ( $input ) {
case \'billing_first_name\':
case \'shipping_first_name\':
return $current_user->user_firstname;
case \'billing_last_name\':
case \'shipping_last_name\':
return $current_user->user_lastname;
case \'billing_email\':
case \'shipping_email\':
return $current_user->user_email;
}
}
return $value;
}