Hello Magento Friends,
Today, I have come up with a solution to get default billing and shipping addresses by customer ID in Magento 2.
Magento 2 allows customers to have multiple billing and shipping addresses associated with their account. Each of these addresses can be used during the checkout process, providing flexibility for customers with different shipping or billing requirements.
Learn – How to Configure Multiple Shipping Addresses in Magento 2.
Customers can also have default billing and shipping addresses set in their customer accounts. Customers can have only one default billing and one default shipping address at a time. These addresses are convenient for returning customers as they can quickly select them during the checkout process, but customers can always choose to enter a new address if needed.
Let’s find out How to Get Default Billing and Shipping Address by Customer ID in Magento 2.
Contents
Step 1: Create a block file at the given path below.
{{magento_root}}\app\code\Vendor\Extension\Block\AddressBook.php
Now add the code as follows.
<?php namespace Vendor\Extension\Block; class AddressBook extends \Magento\Framework\View\Element\Template { protected $accountManagement; public function __construct( \Magento\Framework\View\Element\Template\Context $context, \Magento\Customer\Api\AccountManagementInterface $accountManagement, array $data = [] ) { $this->accountManagement = $accountManagement; parent::__construct($context, $data); } public function getDefaultShippingAddress($customerId) { try { $address = $this->accountManagement->getDefaultShippingAddress($customerId); } catch (NoSuchEntityException $e) { return __('You have not added default shipping address.'); } return $address; } public function getDefaultBillingAddress($customerId) { try { $address = $this->accountManagement->getDefaultBillingAddress($customerId); } catch (NoSuchEntityException $e) { return __('You have not added default billing address.'); } return $address; } }
This way, you can get the default billing and shipping address by customer ID in Magento 2. If you have any doubts about the above method or if you face any errors, connect with me through the comment section. Share the tutorial with your friends and stay in touch with us so that you do not miss out on any important Magento solution from us.
Happy Coding!
Hello Magento Friends, In today’s blog, I will explain How to Add Tooltip in Checkout…
MongoDB is a popular NoSQL database that offers flexibility and scalability when handling modern web…
In NodeJS, callbacks empower developers to execute asynchronous operations like reading files, handling requests, and…
Hello Magento Friends, In today’s blog, we will learn How to Show SKU in Order…
The "Buy Now" and "Add to Cart" buttons serve as the primary call-to-action (CTA) elements…
Hello Magento Friends, In Magento 2, the checkout process allows customers to choose multiple shipping…