Search code examples
phpwordpresswoocommercehook-woocommercecheckout

Fill out woocommerce checkout fields with user meta data


When woocommerce checkout page loads, some fields (like first_name, last_name, state) are prefilled.

But other fields (phone, city, postcode) are empty.

All of checkout fields' data are available in user meta data.

How can I fill checkout field's with user meta data? I tried some codes like this by adding it to my functions.php file.

Have any advice? Regards,

add_filter( 'woocommerce_checkout_fields', 'itdoc_remove_fields', 9999 );


function itdoc_remove_fields( $woo_checkout_fields_array ) {
    
    $user = wp_get_current_user();
    $dealer_phone= get_user_meta($user->ID, 'phone' , true);
    $dealer_city= get_user_meta($user->ID, 'dealer_city' , true);
    $dealer_state= get_user_meta($user->ID, 'postcode' , true);
    print($dealer_phone);

    $woo_checkout_fields_array['billing']['billing_phone']['default'] = $dealer_phone ;
    $woo_checkout_fields_array['billing']['billing_city']['default'] = $dealer_city;
    $woo_checkout_fields_array['billing']['billing_postcode']['default'] = $dealer_postcode;
    var_dump($woo_checkout_fields_array);


    return $woo_checkout_fields_array;
}

// This does not any effect on checkout fields


Solution

  • You are not using the right hook for that, try the following instead:

    add_filter( 'woocommerce_checkout_get_value', 'autofill_some_checkout_fields', 10, 2 );
    function autofill_some_checkout_fields( $value, $input ) {
        $user = wp_get_current_user();
        
        if( $input === 'billing_phone' && empty($value) && isset($user->phone) ) {
            $value = $user->phone;
        }
        
        if( $input === 'billing_city' && empty($value) && isset($user->dealer_city) ) {
            $value = $user->dealer_city;
        }
        
        if( $input === 'billing_postcode' && empty($value) && isset($user->postcode)  ) {
            $value = $user->postcode;
        }
        return $value;
    }
    

    It should work.