Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save shameemreza/2897290889c6c9a1b88a6087dad5ec6b to your computer and use it in GitHub Desktop.

Select an option

Save shameemreza/2897290889c6c9a1b88a6087dad5ec6b to your computer and use it in GitHub Desktop.
Fixes Distance Rate Shipping not updating during checkout when address fields (like city or postcode) change within the same state. Adds JS to trigger recalculation and clears transients server-side to force fresh rate calculation.
/**
* Force recalculation of shipping rates when address fields change during checkout
* Fixes issue with Distance Rate Shipping not updating for address changes within the same state
*/
function wooninja_force_shipping_recalculation() {
if ( ! is_checkout() ) {
return;
}
?>
<script type="text/javascript">
jQuery(function($) {
// These are the fields we want to watch for changes
var addressFields = [
'#shipping_address_1',
'#shipping_address_2',
'#shipping_city',
'#shipping_postcode',
'#shipping_state',
'#shipping_country'
];
// Watch for changes in any address field
$(document.body).on('change', addressFields.join(', '), function() {
console.log('Address field changed, updating checkout...');
// Clear the distance rate shipping cache by adding a timestamp to the post data
$(document.body).on('update_checkout', function(event, args) {
if (args && args.update_shipping_method) {
// Add current timestamp to force cache refresh
args.force_distance_recalc = new Date().getTime();
}
});
// Trigger update checkout
$(document.body).trigger('update_checkout');
});
});
</script>
<?php
}
add_action('wp_footer', 'wooninja_force_shipping_recalculation');
/**
* Clear distance rate shipping cache when checkout is updated
*/
function wooninja_clear_distance_rate_cache($post_data) {
global $wpdb;
// Parse the post data
parse_str($post_data, $data);
// Check if our marker is present, or if shipping address fields changed
$address_fields_changed = isset($data['force_distance_recalc']) ||
isset($data['shipping_address_1']) ||
isset($data['shipping_city']) ||
isset($data['shipping_postcode']);
if ($address_fields_changed) {
// Delete all transients related to distance rate shipping
$wpdb->query("DELETE FROM {$wpdb->options} WHERE option_name LIKE '%_transient_distance_rate_shipping_%'");
$wpdb->query("DELETE FROM {$wpdb->options} WHERE option_name LIKE '%_transient_timeout_distance_rate_shipping_%'");
}
}
add_action('woocommerce_checkout_update_order_review', 'wooninja_clear_distance_rate_cache', 10, 1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment