Magento 2 – get customer shipping address
In this tutorial I show you how to programmatically get customer shipping address. You will need to do this, if you want to implement custom queries based on customers address data. My source code shows you how to get this data and how to display it in your frontend.
Magento 2 – get customer shipping address
If you want to get customer data, you need a logged in user. So for this it is extremely important, that you also cover the case of not logged in users. You can get data of current logged in customers by using customer session object. For this I inject \Magento\Customer\Model\Session in my block class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | protected $customerSession; public function __construct( ... \Magento\Customer\Model\Session $customerSession ) { ... $this->customerSession = $customerSession; parent::__construct($context); } public function getCustomerDeliveryPostcode() { $customer = $this->customerSession->getCustomer(); if ($customer) { $shippingAddress = $customer->getDefaultShippingAddress(); if ($shippingAddress) { return $shippingAddress->getPostcode(); } } return null; } |
Once injected, you can get customer object anytime by calling getCustomer() method. You need to check if you got a customer, because it is possible, that a shop user my not be logged in! You then get all data by calling appropriate methods. If you want your default shipping address, simply call getDefaultShippingAddress(). Again it is possible, that your customer has no address.
Frontend
On your frontend *.phtml file you may get a postcode the following way:
1 2 | //get customer delivery postcode $postcode = $block->getCustomerDeliveryPostcode(); |
You postcode variable now contains a valid postcode or null, if there is no logged in user or a user currently has no shipping address. With $block you get your block class that corresponds to this *.phtml file. This is configured in *.xml layout files. For more details on how to write Magento 2 modules, see my other posts.
Conclusion
Extending a given block to get customer shipping address is quite easy with injecting the correct class. You only need to write a getter method to use this information in your frontend.