Skip to main content

Magento: Disable shipping method for PO Box address


UPS will not ship to PO Box addresses. So, we need to disable the UPS if the customer address has PO Box. USPS has to be shown, as it ships to PO Box addresses. So, here is a code on how to disable the shipping method for PO Box address.

Create a new custom module.
First we need to override the class Mage_Usa_Model_Shipping_Carrier_Ups. Add the below code to the new class to dispatch a custom event. This event can be thrown from any carrier class. So, we can re-use it if to disable any other shipping method.


public function proccessAdditionalValidation(Mage_Shipping_Model_Rate_Request $request) {

    Mage::dispatchEvent('carrier_process_additional_validation', array('request' => $request, 'carrier' => $this));
    if ($this->getCarrierNotAvailable() === true) {
        return false;
    }

    return parent::proccessAdditionalValidation($request);
}

Add the below code to etc/system.xml file.


<config>
    <sections>
        <carriers>
            <groups>
                <ups>
                    <fields>
                        <po_box_disable translate="label">
                            <label>Disable if PO Box in the address</label>
                            <frontend_type>select</frontend_type>
                            <source_model>adminhtml/system_config_source_yesno</source_model>
                            <sort_order>5000</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                        </po_box_disable>
                    </fields>
                </ups>
            </groups>
        </carriers>
    </sections>
</config>

Catch the event "carrier_process_additional_validation" in the observer.


public function proccessAdditionalValidation($observer) {
    $request = $observer->getEvent()->getRequest();
    $carrier = $observer->getEvent()->getCarrier();

    if ($carrier->getConfigData('po_box_disable')) {
        $street = $request->getData('dest_street');
        if (preg_match("/p(ost)?\.?\s*o(ffice)?\.?\s*(b(ox)?)?\.?\s*\d+/i", $street)) {
            $carrier->setCarrierNotAvailable(true);
        }
    }

    return $this;
}


Comments

Popular posts from this blog

Magento 2 - Create a simple module

In magento 2, the creation of module has changed completely. We will go through how to create a module. Like earlier magento, we do not need to put our module files in different folders for code, theme, skin, etc. All, the codes related to the module should be inside one main folder. You can find the sample code in the git repo .