1

I have converted the postcode field in checkout to a dropdown field. Its working fine.

$fields['billing']['billing_postcode'] = array(
    'type' => 'select',
    'label'     => __('Locality - Postcode', 'woocommerce'),
    'placeholder'   => _x('Select a locality', 'placeholder', 'woocommerce'),
    'required'  => true,
    'class'     => array('form-row-first'),
    'clear'     => false
     ); 

This is getting updated in the db and values show on order invoice. Now how would I show the already stored value of postcode field as selected option in the checkout fields. For ex: How the name is auto populated for a registered customer based on his earlier order. I have tried a few functions, but no relief. Kindly advice somebody!

1 Answer 1

1

I just had a similar problem and solved it with a combination of PHP and jQuery.

If $stored_value is what you have pulled from the DB and #billing_postcode is the id of the select-tag:

<?php if ( !empty( $stored_value ) ) { ?>
<script type="text/javascript">
    jQuery(document).ready(function($) {
        $("select#billing_postcode").val( "<?php echo $stored_value; ?>" );
    });
</script>
<?php } ?>

I use this inside a function that I apply to the "woocommerce_checkout_fields" filter.

Update 1: After a little bit more research I found out that I can also just do this:

<?php if ( !empty( $stored_value ) ) {
$fields['billing']['billing_postcode']['default'] = $stored_value;
} ?>

Update 2:

In functions.php of my theme, I put it in like this:

<?php
// Hook in
add_filter( 'woocommerce_checkout_fields' , 'jsm_override_checkout_fields' );

function jsm_override_checkout_fields( $fields ) {

    $stored_value = "something pulled from the DB";

    if ( !empty( $stored_value ) ) {
    $fields['billing']['billing_postcode']['default'] = $stored_value;
    }

    return $fields;
} ?>
2
  • Thanks Jakob for helping, but where would this piece of code go into? I have already tried this on similar lines which does not work in functions.php $current_user = wp_get_current_user(); $fields['billing']['billing_postcode']['default'] = $current_user->billing_postcode; return $fields;
    – Anith
    Mar 4, 2016 at 6:11
  • @Anith See Update 2 in my original answer. Mar 7, 2016 at 21:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.