You can change the billing or shipping address for an order separately programmatically in Magento 2 by using the Magento\Sales\Api\OrderAddressRepositoryInterface
interface.
Here is an example of how to change the billing address programmatically:
use Magento\Sales\Api\OrderAddressRepositoryInterface;
use Magento\Sales\Model\Order;
class ChangeBillingAddress
{
protected $orderAddressRepository;
public function __construct(
OrderAddressRepositoryInterface $orderAddressRepository
) {
$this->orderAddressRepository = $orderAddressRepository;
}
public function execute(Order $order, array $billingAddressData)
{
$billingAddress = $order->getBillingAddress();
$billingAddress->addData($billingAddressData);
$this->orderAddressRepository->save($billingAddress);
}
}
In this example, the OrderAddressRepositoryInterface is injected in the class constructor, and the execute() method takes an Order object and an array of billing address data as parameters. The billing address data should include the fields that you want to update, such as the first name, last name, street address, city, etc.
To change the shipping address programmatically, you can use a similar approach, but instead of calling $order->getBillingAddress(), you would call $order->getShippingAddress()
to get the shipping address object.