1
votes

In WooCommerce, at checkout, I am able to create or update all the user and billing information while placing an order. However, I want to set/update the user "display name" (alias) as well.

So based on "Capture custom checkout field value in Woocommerce" answer code, I have added the following code to my active theme's functions.php file:

// Display a custom checkout field
add_action( 'woocommerce_before_checkout_billing_form', 'my_custom_checkout_field' );
function my_custom_checkout_field( $checkout ) {
    echo '<div id="my_custom_checkout_field">';

    woocommerce_form_field( 'display_name', array(
        'type'          => 'text',
        'class'         => array('my-custom-field form-row-wide'),
        'label'         => __('Alias'),
        'placeholder'   => __('Nickname to show in my account and comments'),
        'required'      => true,
        ), $checkout->get_value( 'display_name' ));

    echo '</div>';
}

// Save the custom checkout field in the order meta
add_action( 'woocommerce_checkout_update_user_meta', 'save_order_custom_meta_data', 10, 2 );
function save_order_custom_meta_data( ) {
    if ( isset($_POST['display_name']) )
        $user->update_meta_data('display_name', sanitize_text_field( $_POST['display_name'] ) );
}

But this is not working as I get "Internal Server Error" message.

Any help to solve this will be appreciated.

1

1 Answers

2
votes

The problem comes from your second function… The function arguments are missing and $user variable is null and you can't use on it the WC_Data method update_meta_data().

Also the display_name is not user meta data, but simply user data. So you need to use dedicated WordPress function wp_update_user() in order to set/update the user display name.

Replace your 2nd hooked function with the following instead:

// Save/update user data from custom checkout field value
add_action( 'woocommerce_checkout_update_user_meta', 'checkout_update_user_display_name', 10, 2 );
function checkout_update_user_display_name( $customer_id, $data ) {
    if ( isset($_POST['display_name']) ) {
        $user_id = wp_update_user( array( 'ID' => $customer_id, 'display_name' => sanitize_text_field($_POST['display_name']) ) );
    }
}

Code goes in function.php file of your active child theme (or active theme). It should works now.