Skip to content
Advertisement

Pre-filing checkout post code with a custom value

I have been using this custom function below in the previous versions of WooCommerce in order to pre-fill the City and ZIP code fields:

add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' );

function custom_override_checkout_fields( $fields ) {
     $fields['billing']['billing_city']['default'] = 'Beverly Hills';
     $fields['billing']['billing_postcode']['default'] = '90210';
     return $fields;
}

It has been working great until the new WC updates.

The city still works, but the default ZIP code field doesn’t seem to work anymore. It doesn’t automatically pre-polulate the value.

Anything changed? Is there any other workaround for this?

Thanks

Advertisement

Answer

Setting a value for ‘post-code’ fields doesn’t work anymore as there is an autocomplete feature. Even when disable “autocomplete”, this doesn’t work. So the workaround is to use jQuery in this case.

So your code is going to be:

add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields', 10, 1 );
function custom_override_checkout_fields( $fields ) {

    $fields['billing']['billing_city']['default'] = 'Beverly Hills';
    $fields['billing']['billing_postcode']['autocomplete'] = "off"; // Removing autocomplete

    return $fields;
}

add_action( 'woocommerce_after_checkout_form' , 'my_custom_checkout_field_postcode' );
function my_custom_checkout_field_postcode( ) {
    ?>
        <script>
            (function($){
                $('#billing_postcode').val('90210');
            })(jQuery);
        </script>
    <?php
}

This will set correctly your the desired value in “post-code” checkout billing field.

The Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement