Magento – Use USPS Shipping Method for APO Address Only

magento-1.7shipping

How can I enabled USPS Shipping method for APO Addresses Only? I have USPS working fine, however we only want to use it for US military addresses (APO, FPO or DPO) only. Our primary shipping method is UPS which is working fine, however our customers are now selecting USPS address and we are loosing money on those shipping methods.

How can I lock down USPS shipping method to only be an option for APO addresses? Currently in Magento backend there is only options to select Applicable Countries.

Thanks

Best Answer

I used the following code in my ../template/checkout/onepage/shipping_method/available.phtml custom theme template inside the foreach shippingrategroups loop....

USPS and additional shipping methods must be enabled. It forces any APO address to USPS if it finds a city or region code that matches.

         <?php //Added to force USPS for APO
            $address = $this->getAddress();
            $apoStateCodes = array("AE", "AE", "AP");
            $apoCityCodes = array("APO", "FPO", "DPO");

            $regionCode = Mage::getModel('directory/region')->load($address->getRegionId())->getCode();

            $carrierName = strtoupper(str_replace(" ", "", $this->getCarrierName($code)));
            if (in_array($regionCode, $apoStateCodes) || in_array($address->getCity(), $apoCityCodes))
            {
                // IT IS APO, so skip iteration of non-USPS
                if ($carrierName != "USPS")
                {
                    continue;
                }
            }
            else
            {
                // ITS A NORMAL ADDRESS
                if ($carrierName == "USPS")
                {
                    continue;
                }
            }

            /* OLD WAY OF DOING THINGS (only works on PO box)
            if (preg_match("/p\.* *o\.* *box/i", $this->htmlEscape($this->getAddress()->getStreet(1))))
            {
                $carrierName = strtoupper(str_replace(" ", "", $this->getCarrierName($code)));
                if ($carrierName != "UNITEDSTATESPOSTALSERVICE")
                {
                    continue;
                }
            }
            */
         ?>