php - Flat Rate Shipping Based on custom region dropdown field

admin2025-01-08  3

i have custom dropdown field on checkout page For region select. Have 2 rate:

  1. For Region X with cost 5$ (flat-rate:34)
  2. 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

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736268701a1295.html

最新回复(0)