i have custom dropdown field on checkout page For region select. Have 2 rate:
- For Region X with cost 5$ (flat-rate:34)
- Second for all others with cost 10$ (flat-rate:35)
I want to set rates on field change.
// Enqueue custom JavaScript for detecting region change inline
add_action('wp_footer', 'add_inline_region_shipping_js');
function add_inline_region_shipping_js() {
// Only add the script on the checkout page
if (is_checkout()) {
?>
<script type="text/javascript">
jQuery(function($) {
// Listen for changes on the region dropdown
$('#easyway_region').change(function() {
// Trigger WooCommerce's checkout update after changing the region
$('body').trigger('update_checkout');
});
});
</script>
<?php
}
}
// Adjust available shipping rates based on the selected region in the checkout form
add_filter('woocommerce_package_rates', 'adjust_shipping_methods_based_on_region', 10, 2);
function adjust_shipping_methods_based_on_region($rates, $package) {
// Get the selected region from the checkout form
$region = isset($_POST['easyway_region']) ? sanitize_text_field($_POST['easyway_region']) : '';
// Tbilisi Region ID (ID 24, update if needed)
if ($region == '24') {
// Only allow the Tbilisi shipping rate (flat_rate:34)
foreach ($rates as $rate_key => $rate) {
if ($rate->method_id !== 'flat_rate' || $rate->id !== 'flat_rate:34') {
unset($rates[$rate_key]); // Remove non-Tbilisi rates
}
}
} else {
// Only allow the other region shipping rate (flat_rate:35)
foreach ($rates as $rate_key => $rate) {
if ($rate->method_id !== 'flat_rate' || $rate->id !== 'flat_rate:35') {
unset($rates[$rate_key]); // Remove non-other region rates
}
}
}
return $rates;
}
need to fix this one
$('body').trigger('update_checkout');
, isupdate_checkout
and ID or a CLASS? If it's the button ID, it should be$('body').trigger('#update_checkout');
if it's the button CLASS name it should be$('body').trigger('.update_checkout');
. If that's NOT it, please update us as to what specifically is happening.update_checkout
so that something triggers it and I don't think your script knows what that is. Isupdate_checkout
a button? And is thatid="update_checkout"
or is itclass="update_checkout"
?