Restrict zip codes for custom shipping method is not working after hide the shipping method

Restrict zip codes for custom shipping method is not working after hide the shipping method

September 9, 2026 · Illustrated author avatarBy Stefan Bogdanescu
Restrict zip codes for custom shipping method is not working after hide the shipping method

Shipping is an integral part of any e-commerce platform, enabling businesses to deliver goods to customers worldwide. In Magento 2, shipping calculations can be complex, especially when dealing with multiple sellers or regional shipping charges. This post will guide you through implementing regional shipping in your Magento 2 project.

Understanding Regional Shipping

Regional shipping allows sellers to set different shipping rates based on the geographical location of the buyer and seller. This is particularly useful for businesses operating across multiple regions with varied shipping costs. In Magento 2, this can be achieved using the Carrier Model and custom shipping methods.

Setting Up a Custom Shipping Method

To begin, create a new shipping method in your module’s config.xml file:

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd">
    <default>
        <carriers>
            <your_module_code>
                <active>1</active>
                <title>Your Custom Module Title</title>
                <sort_order>0</sort_order>
            </your_module_code>
        </carriers>
    </default>
</config>

This configuration enables your custom shipping method (replace your_module_code and Your Custom Module Title with your actual values). Next, you’ll need to implement the shipping logic.

Implementing Regional Shipping Logic

Open your module’s etc/carrier.xml file and add the following code:

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd">
    <carriers>
        <your_module_code>
            <price_expression>base_shipping_amount * 1</price_expression>
            <specific_error_messages>
                <messages>
                    <item>
                        <title translate="true">Shipping Error</title>
                        <error_message translate="true">There is an issue with your shipping address. Please contact customer support.</error_message>
                    </item>
                </messages>
            </specific_error_messages>
        </your_module_code>
    </carriers>
</config>

This configuration sets the base calculation for shipping charges and defines an error message.

Calculating Shipping Charges

To calculate regional shipping charges, you’ll need to create a new method in your module’s Model/Carrier/YourModule.php file:

class YourModule extends \Magento\Shipping\Model\Carrier\AbstractCarrier implements \Magento\Shipping\Model\Carrier\CarrierInterface
{
    protected $_code = 'your_module_code';

    public function collectRates(\Magento\Quote\Model\Quote\Item $item) {
        // Your shipping calculation logic here
        return [];
    }
}

In the collectRates method, you’ll need to calculate the shipping charges based on the buyer’s and seller’s location. A common approach is to use the Google Maps Distance Matrix API to determine the distance between two locations.

Implementing the Distance Calculation

To use the Google Maps Distance Matrix API, you’ll first need an API key. You can obtain one from the Google Cloud Console. Once you have a key, you can make a request to the API using cURL:

$url = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=".$origin.",india&amp;destinations=".$destination.",india&amp;mode=driving&amp;language=en-EN&amp;sensor=false";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// ... other cURL settings ...
$response = curl_exec($ch);
curl_close($ch);

The response from the API contains information about the distance between two locations. You can extract the distance value and use it in your shipping calculation.

Setting Regional Shipping Charges

To set regional shipping charges, you’ll need to create custom product attributes for each region (e.g., “Regional Shipping Charge”). In your collectRates method, retrieve these attributes using the following code:

$mpshippingcharge=Mage::getModel('catalog/product')->load($item->getProductId())->getMpRegionalShippingCharge();

This retrieves the regional shipping charge for a specific product.

Calculating Total Shipping Costs

Finally, in your collectRates method, calculate the total shipping cost by summing up the individual shipping charges:

$price = 0;
foreach ($items as $item) {
    // Calculate shipping charge for each item
    // ...
    if(!is_numeric($mpshippingcharge)){
        $price=$price+floatval($this->getConfigData('defalt_ship_amount')* floatval($item->getQty()));
    }else{
        $price=$price+($mpshippingcharge * floatval($item->getQty()));
    }
}

This calculates the total shipping cost based on the regional shipping charges and the quantity of each item.

Displaying Shipping Information

To display the calculated shipping information, you’ll need to override the onepage.phtml template located at app/design/frontend/default/em0113/template/checkout/onepage.phml:

<ol class="opc" id="checkoutSteps">
    <?php $i=0; foreach($this->getSteps() as $_stepId => $_stepInfo): ?>
        <?php if (!$this->getChild($_stepId) || !$this->getChild($_stepId)->isShow()): continue; endif; $i++ ?>
        <li id="opc-<?php echo $_stepId ?>" class="section<?php echo !empty($_stepInfo['allow'])?' allow':'' ?><?php echo !empty($_stepInfo['complete'])?' saved':'' ?>">
            <!-- ... rest of the template code ... -->
        </li>
    <?php endforeach ?>
</ol>

This displays the shipping steps in the checkout process.

Conclusion

In this post, we’ve explored how to implement regional shipping in Magento 2 using custom shipping methods and the Google Maps Distance Matrix API. By following these steps, you can provide tailored shipping options for your customers based on their location.

For more information on Magento 2 development, visit https://laravelcompany.com for additional tutorials and resources.

Magento 2 API Extensions Configuration

Our network