Milind Daraniya

How to Get Default Billing and Shipping Address by Customer ID in Magento 2

Published September 1st, 2023 12 min read

Hey Magento developers! Today, we'll learn how to retrieve the default billing and shipping address of a customer using their ID in Magento 2. This handy script will allow you to streamline your checkout process and provide a better user experience for your customers. Let's dive right in!

First, make sure you have a basic understanding of Magento 2 development and access to your Magento 2 codebase. Then, follow these steps to create the script:

Step 1: Create a new PHP file 
In your Magento 2 project, create a new PHP file named "GetCustomerAddresses.php" or any other suitable name you prefer.

Step 2: Set up the initial code 
In the newly created file, start by including the Magento bootstrap file to initiate the Magento environment:

<?php
use Magento\Framework\App\Bootstrap;

require __DIR__ . '/app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);

// Object Manager to retrieve data
$objectManager = $bootstrap->getObjectManager();

Step 3: Define the function to get addresses 
Now, create a function to retrieve the default billing and shipping addresses by customer ID:

function getCustomerAddresses($customerId) {
    // Load the customer by ID
    $customer = $objectManager->create('Magento\Customer\Model\Customer')->load($customerId);

    // Get the default billing address
    $billingAddressId = $customer->getDefaultBilling();
    $billingAddress = $objectManager->create('Magento\Customer\Model\Address')->load($billingAddressId);

    // Get the default shipping address
    $shippingAddressId = $customer->getDefaultShipping();
    $shippingAddress = $objectManager->create('Magento\Customer\Model\Address')->load($shippingAddressId);

    return [
        'billing_address' => $billingAddress->getData(),
        'shipping_address' => $shippingAddress->getData(),
    ];
}

Step 4: Usage example 
Now, you can call the getCustomerAddresses function and pass the customer ID to retrieve the default billing and shipping addresses:

Step 5: Run the script 
Save the file and navigate to your Magento 2 root directory using the command line. Then, execute the script by running:

php GetCustomerAddresses.php

The script will output the default billing and shipping addresses for the provided customer ID.

That's it! You now have a working script to get the default billing and shipping addresses by customer ID in Magento 2. Feel free to integrate this functionality into your Magento store to enhance the checkout process for your valued customers.