Update shipping fee on state and postcode change on WooCommerce checkout page

Some theme may already come with the option of automatically updating shipping fee/checkout totals when updating state and/or postcode on WooCommerce checkout page. This is very useful to get proper shipping fee during order. I will say this should be a mandatory option for all themes. But unfortunately, it is not.

We can achieve this simply by adding update_totals_on_change css class on the field. This sometimes doesn’t work, thanks to javascript conflict of some themes. So we will also implement a fail-safe method using update_checkout jQuery event of WooCommerce.

Initial method – adding css class

function careless_trigger_wc_update_checkout_on_change( $fields ) {
    $fields['billing']['billing_state']['class'][] = 'update_totals_on_change';
    $fields['billing']['billing_postcode']['class'][] = 'update_totals_on_change';
    $fields['shipping']['shipping_state']['class'][] = 'update_totals_on_change';
    $fields['shipping']['shipping_postcode']['class'][] = 'update_totals_on_change';

    return $fields;
}
add_filter( 'woocommerce_checkout_fields' , 'careless_trigger_wc_update_checkout_on_change' );

Fail-safe method

function careless_trigger_wc_update_checkout_on_change_via_js() {
    //only on checkout page
    if ( !is_checkout() ) {
        return;
    } ?>
    <script>
        jQuery("#billing_postcode").blur(function(){
            jQuery( 'body' ).trigger( 'update_checkout' );
        });
        jQuery("#shipping_postcode").blur(function(){
            jQuery( 'body' ).trigger( 'update_checkout' );
        });
        jQuery("#billing_state").blur(function(){
            jQuery( 'body' ).trigger( 'update_checkout' );
        });
        jQuery("#shipping_state").blur(function(){
            jQuery( 'body' ).trigger( 'update_checkout' );
        });
    </script>
    <?php
}
add_action( 'wp_footer','careless_trigger_wc_update_checkout_on_change_via_js' );

Code goes in the functions.php file of your active theme.