But, from what I can tell, this is only set to fire when a user
updates their own profile.
Yes, that’s correct.
Running it as I created a user account didn’t produce the results I
was looking for.
The hook you should use when the user is being created/registered, is user_register
.
So you would use this, where you hook to both profile_update
and 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' );
And since the second hook (user_register
) only provides one parameter, then just omit the $old_user_data
from the function; and secondly, you should use get_userdata()
and not wp_get_current_user()
to get the user being updated or created.
The full code I used:
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 );
}
Note though, the user_register
hook wouldn’t be called if the customer is anonymous and not allowed to create a WordPress/user account.
Additional Code
You can use the woocommerce_checkout_get_value
hook to auto-fill the form data, although WooCommerce actually does the auto-fill if the metadata exist.
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;
}