To include customer address attributes in the Order Data API, Please follow the below steps.
- In your module, create an
etc/extension_attributes.xml file to declare the extension attribute.
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Api/etc/extension_attributes.xsd"> <extension_attributes for="Magento\Sales\Api\Data\OrderInterface"> <attribute code="custom_attribute" type="string" /> </extension_attributes> </config>
- Create a
etc/di.xml file to define a plugin.
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> <type name="Magento\Sales\Api\OrderRepositoryInterface"> <plugin name="add_custom_attribute_to_order_data" type="Vendor\Module\Plugin\OrderRepositoryPlugin"/> </type> </config>
- Create a
Plugin/OrderRepositoryPlugin.php to get the customer address attribute and set it into order data.
You need to inject the Magento\Customer\Api\AddressRepositoryInterface into your plugin.
<?php namespace Vendor\Module\Plugin; class OrderRepositoryPlugin { protected $addressRepository; public function __construct( \Magento\Customer\Api\AddressRepositoryInterface $addressRepository ) { $this->addressRepository = $addressRepository; } public function afterGet( \Magento\Sales\Api\OrderRepositoryInterface $subject, \Magento\Sales\Api\Data\OrderInterface $order ) { $billingAddressId = $order->getBillingAddressId(); $address = $this->addressRepository->getById($billingAddressId); $customAttribute = $address->getCustomAttribute('custom_attribute'); if ($customAttribute) { $order->setCustomAttribute($customAttribute->getValue()); } return $order; } public function afterGetList( \Magento\Sales\Api\OrderRepositoryInterface $subject, \Magento\Sales\Api\Data\OrderSearchResultInterface $searchResult ) { foreach ($searchResult->getItems() as $order) { $this->afterGet($subject, $order); } return $searchResult; } }
We can get the billing address ID from the order, using the address repository to load the address, and then get the custom attribute from the address and we can set it to the order data.