Woocommerce checkout field based on postcode

Viewed 77

I have a radio custom field on checkout. I need to populate the options of the radio field based on the selected postcode. If the postcode changes, i need to update the options.

add_filter('woocommerce_after_checkout_billing_form', 'cc_custom_checkout_fields');
function cc_custom_checkout_fields($checkout)
{
    woocommerce_form_field('deliveryhours', array(
        'type'          => 'radio', 
        'required'    => false,
        'class'         => array('form-row-wide'),
        'options'     => array(
            '' => __('Select:'),
            'F1' => __('11:00 – 13:00'),
            'F2' => __('13:00 – 15:00'),
            'F3' => __('16:00 – 17:30'),
            'F4' => __('17:30 – 19:00'),
            'F5' => __('19:00 – 21:00')
        )
    ), $checkout->get_value('deliveryhours'));
}

How can I achieve that?

Thanks!

1 Answers

If you want to reset the form field from postal code fields, you should use jquery inside your custom field function like this:

  add_filter('woocommerce_after_checkout_billing_form', 'cc_custom_checkout_fields');
  function cc_custom_checkout_fields($checkout)
  {
        woocommerce_form_field('deliveryhours', array(
        'type'          => 'radio', 
        'required'    => false,
        'class'         => array('form-row-wide'),
        'options'     => array(
              '' => __('Select:'),
              'F1' => __('11:00 – 13:00'),
              'F2' => __('13:00 – 15:00'),
              'F3' => __('16:00 – 17:30'),
              'F4' => __('17:30 – 19:00'),
              'F5' => __('19:00 – 21:00')
        )
        ), $checkout->get_value('deliveryhours'));

        wc_enqueue_js( "
              // On change Postalcode. #billing_postcode => postal code input field id
              jQuery(document).on('blur','#billing_postcode',function() {
                    var postcode = jQuery(this).val();  
                    if(postcode){
                          jQuery('#deliveryhours_field .input-radio').first().prop('checked', true); // reset radio
                          jQuery(document.body).trigger('update_checkout'); // update checkout 
                    }
              });
        ");
  }

You can also modify conditions accordingly.

Related