I’m curious to know how many had the same problem. At WooCommerce checkout, some user fields such as billing_name, shipping_address_1, etc. are automatically saved into the “WordPress User Profile” upon processing.
But what if we also wanted to display and save another existing user field, such as “user_twitter”, or “user_url”, which you can find in the WP User Profile by default? Well, this is very easy: first, we add a custom checkout field; then, we make sure that when the checkout is processed we save that field correctly!
Display & save a default WordPress User Field via WooCommerce Checkout
PHP Snippet: Show & Save WordPress User Field Upon WooCommerce Checkout
/**
* @snippet Display & Save WP User Field @ Checkout - WooCommerce
* @how-to Get tutoraspire.com FREE
* @sourcecode https://tutoraspire.com/?p=21737
* @author Tutor Aspire
* @compatible WC 3.5.1
*/
// ------------------------
// 1. Display field @ Checkout
add_action( 'woocommerce_after_checkout_billing_form', 'tutoraspire_add_user_field_to_checkout' );
function tutoraspire_add_user_field_to_checkout( $checkout ) {
$current_user = wp_get_current_user();
$saved_url = $current_user->user_url;
woocommerce_form_field( 'user_url', array(
'type' => 'text',
'class' => array('user_url form-row-wide'),
'label' => __('Website URL'),
'placeholder' => __('https://yoursite.com'),
'required' => false
),
$saved_url );
}
// ------------------------
// 2. Save Field Into User Meta
add_action( 'woocommerce_checkout_update_user_meta', 'tutoraspire_checkout_field_update_user_meta' );
function tutoraspire_checkout_field_update_user_meta( $user_id ) {
if ( $user_id && $_POST['user_url'] ) {
// once again, use "user_url"
$args = array(
'ID' => $user_id,
'user_url' => esc_attr( $_POST['user_url'] )
);
wp_update_user( $args );
}
}