Merge Guest Order with Registered Customer – Magento2

Merge Guest Order with Registered Customer – Magento2

Hello Guys

Welcome back to Our Blog, Hope you are staying safe!
In Today’s Blog we are explaining Step by Step how you can merge your guest orders with your registered customer,
Sometime your registered customer place order as guest in your website, So You can merge that order with your registered customer so customer can manage his order which he placed as guest.
So First of all you need to create a Module.
Here we are creating a module name MagentoAcademy/MergeCustomer
In Module we are creating registration.php
 * Module configuration
Now we will create etc/module.xml
<?xml version="1.0"?>
<config xmlns:xsi="" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="MagentoAcademy_MergeCustomer" setup_version="1.0.0">
        <module name="Magento_Customer"/>
        <module name="Magento_Sales"/>

Here you can see we have added sequence Magento_Customer and Magento_Sales,
This I have added bcz here we are using Customer and Orders both So it should
be your dependent module bcz without this module your MergeCustomer module is not for use

Now you need to create an etc/events.xml file

<?xml version="1.0"?>
<config xmlns:xsi="" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="sales_order_place_after">
        <observer name="sales_order_place_after_event" instance="MagentoAcademy\Sales\Observer\SalesOrderPlaceAfter" />
Now Create Observer/SalesOrderPlaceAfter.php
namespace MagentoAcademy\Sales\Observer;

use Magento\Customer\Model\ResourceModel\CustomerRepository;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Event\Observer;
use Magento\Framework\Exception\LocalizedException;

class SalesOrderPlaceAfter implements ObserverInterface
    public function __construct(CustomerRepository $customerRepository)
        $this->customerRepository = $customerRepository;
     * @param Observer $observer
     * @throws \Magento\Framework\Exception\LocalizedException
    public function execute(Observer $observer)
        $order = $observer->getEvent()->getOrder();

        if($order->getCustomerIsGuest()) {
    public function mergeGuestOrders($order)
        $customerEmail = $order->getCustomerEmail();

            $customer = $this->customerRepository->get($customerEmail);

            if (!empty($customer)) {
        }catch (LocalizedException $e) {

}//end class
Now Enable this module by run below command
php bin/magento module:enable Magento_Academy
and run php upgrade command
php bin/magento setup:upgrade
and lastly flush your cache
php bin/magento cache:flush
You can Download Our Merge Order to Guest Magento2 Extension from MarketPlace as well for free
Hope this solution will help in your Business
Thanks and Keep Visiting our blog! and also Please subscribe to know more.
Leave a Reply
Your email address will not be published. *