questions

Refresh a printed value on some shipping field change in WooCommerce Checkout

Rate this post

I have this code which prints the shipping country selected by the user in the woocommerce checkout page (shipping form). It works fine, the value get printed when the checkout page get loaded.

But then, if the user changes the selected country in the select list (in shipping form) the printed country value gets outdated. There is an ajax event which refresh the delivery charges, etc. But my value does not get updated.

Question: is there a way to call again the ‘action’ when the user makes changes in the shipping form?

<?php
add_action( 'woocommerce_checkout_before_order_review', 'action_woocommerce_checkout_before_order_review', 10, 0 );

function action_woocommerce_checkout_before_order_review () {
        echo $country = WC()->customer->get_shipping_country();
}    

 

✔️Solution:

Finally Ajax is not required, just adding a surrounding html tag to the displayed country and using a little bit of jQuery, you can refresh the displayed shipping country code as follows:

add_action( 'woocommerce_checkout_before_order_review', 'action_woocommerce_checkout_before_order_review' );
function action_woocommerce_checkout_before_order_review () {
    echo '<span class="the_shipping_country">'. WC()->customer->get_shipping_country() . '</span>';
}

// JQuery code
add_action( 'wp_footer', 'checkout_shipping_country_refresh_display' );
function checkout_shipping_country_refresh_display() {
    // On checkout
    if ( is_checkout() && ! is_wc_endpoint_url() ) :
    ?><script type="text/javascript">
    jQuery( function($){
        // Shipping fias code change & input events
        $(document.body).on( 'change', 'select[name=shipping_country]', function() {
            $('.the_shipping_country').html($(this).val());
            console.log($(this).val());
        });
    });
    </script>
    <?php
    endif;
}

Code goes in functions.php file of the active child theme (or active theme). Tested and works.

Leave a Reply

Your email address will not be published.

Back to top button