Get address fields in Magento 2 from an order object.

There are many times during development that I need to get part of, or all or, an order address in Magento 2 development.  For mapping rules in integration or passing the state to a tracking script.

When doing this, for US anyways, here is the code framework I start with:

[code]
/** $order – \Magento\Sales\Model\Order */
$firstName = $order->getShippingAddress()->getFirstName()
$lastName = $order->getShippingAddress()->getLastName();
$address = $order->getShippingAddress()->getStreet(); /** An array of all address lines. $address[0] = address line 1, etc. */
$city = $order->getShippingAddress()->getCity();
$state = $order->getShippingAddress()->getRegionCode();
$zip = $order->getShippingAddress()->getPostCode();
$country = $order->getShippingAddress()->getCountryId();
$telephone = $order->getShippingAddress()->getTelephone();
$total = $order->getGrandTotal();
$shippingAmount = $order->getShippingAmount();
[/code]

Obviously there are additional fields you can get, but these cover the main ones I usually need.

Leave a Reply

Your email address will not be published. Required fields are marked *