Search code examples
phpwordpresswoocommercecart

Show shipping calculator postcode field only for specific countries in WooCommerce


I am using Remove postcode from Woocommerce cart shipping calculator answer code which I tested and works fine.

But the problem is that it hides the postcode of the Shipping Calculator for all countries.

What I would like is to hide it for all countries EXCEPT one: Belgium (BE).

Is this possible? How can I make it work for all countries except Belgium.


Solution

  • I think you can dynamically hide and show the postcode field based on the selected country with some jQuery:

    add_action( 'wp_footer', 'show_shipping_calculator_postcode_field_based_on_country', 50 );
    function show_shipping_calculator_postcode_field_based_on_country() {
        if ( ! is_cart() ) return;
        ?>
        <script type='text/javascript'>
            jQuery(function($){
                $(document.body).on('change', 'select[name="calc_shipping_country"]', function() {
    
                    let country = $(this).find( 'option:selected' ).val();
                    let postcode = $(this).closest( 'p#calc_shipping_country_field' ).siblings( 'p#calc_shipping_postcode_field' ).find('input');
    
                    if ( country !== 'BE' ) {
                        postcode.prop('disabled', true);
                        postcode.attr('value', '');
                        postcode.hide();
                    } else {
                        postcode.prop('disabled', false);
                        postcode.attr('value', '<?php echo WC()->customer->get_shipping_postcode(); ?>');
                        postcode.show();
                    }
                });
            });
        </script>
        <?php
    }
    

    This clears the value of the postcode field, disables it and hides it when the selected country is not Belgium.