How To

How to assign guest customers orders into registered account in Magento 2

In this article, I will help you to learn How to assign guest customer’s orders into a registered account in Magento 2. Also don’t forget to check our previously published How to Add Discount Component to Checkout Order Summary in Magento 2

Basically when any customer places an order from your store being a guest customer and later on that customer registers themself in your store then the orders they place being the guest customers don’t reflect on their account. Therefore to add these orders to the registered account you will require to add the below-given codes into the custom extension.

Steps to assign guest customers orders into registered account in Magento 2:

Step 1: Create Events.xml in the following path

app\code\Vendor\Extension\etc\events.xml

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">

    <event name="customer_save_after_data_object">

        <observer name="customer_save" instance="Vendor\Extension\Observer\Customersave" />

    </event>

</config>

Step 2: Now add Customersave.php in the following path

app\code\Vendor\Extension\Observer\Customersave.php

<?php

namespace Vendor\Extension\Observer;

use Magento\Framework\Event\ObserverInterface;

class Customersave implements ObserverInterface

{

    protected $collectionFactory;

    protected $logger;

    public function __construct(

        \Magento\Sales\Model\ResourceModel\Order\CollectionFactory $collectionFactory,

        \Psr\Log\LoggerInterface $logger

    )

    {

        $this->collectionFactory = $collectionFactory;

        $this->logger = $logger;

    }

    public function execute(\Magento\Framework\Event\Observer $observer)

    {

        try {

            $savedCustomer = $observer->getData('customer_data_object');                  

            $collection = $this->collectionFactory->create()

                ->addAttributeToSelect('entity_id')

                ->addAttributeToSelect('customer_email')

                ->addFieldToFilter('customer_email',

                    ['eq' => $savedCustomer->getEmail()]

                )->addFieldToFilter('customer_is_guest',

                    ['eq' => 1]

                );

            if ($collection->count()) {

                foreach ($collection as $order){

                     $order->setCustomerId($savedCustomer->getId());

                     $order->setCustomerGroupId($savedCustomer->getGroupId());

                     $order->setCustomerIsGuest(1);

                     $order->save();

                }

            }

            return $this;

        } catch (\Exception $e) {

            $this->logger->critical($e->getMessage());

        }

    }

}

Note: The above codes may take the load when the customer registers all the registered customer’s order details loads to set the customer id to each order.

Therefore, we will use the below method to reduce the load. Here we have used raw query so in a single query we will set it to multiple orders.

<?php

namespace Vendor\Extension\Observer;

use Magento\Framework\Event\ObserverInterface;

class Customersave implements ObserverInterface

{

    protected $collectionFactory;

    protected $resourceConnection;

    protected $logger;

    public function __construct(

        \Magento\Sales\Model\ResourceModel\Order\CollectionFactory $collectionFactory,

        \Magento\Framework\App\ResourceConnection $resourceConnection,

        \Psr\Log\LoggerInterface $logger

    )

    {

        $this->collectionFactory = $collectionFactory;

        $this->resourceConnection = $resourceConnection;

        $this->logger = $logger;

    }

    public function execute(\Magento\Framework\Event\Observer $observer)

    {

        try {

            $savedCustomer = $observer->getData('customer_data_object');

            $collection = $this->collectionFactory->create()

                ->addAttributeToSelect('entity_id')

                ->addAttributeToSelect('customer_email')

                ->addFieldToFilter('customer_email',

                    ['eq' => $savedCustomer->getEmail()]

                )->addFieldToFilter('customer_is_guest',

                    ['eq' => 1]

                );

            if ($collection->count()) {

                $gustOrderId = "";

                foreach ($collection as $item) {

                    $gustOrderId .= $item->getId() . ",";

                }

                $gustOrderId = rtrim($gustOrderId, ',');

                $tableName = $this->getTableName('sales_order');

                $sql = "UPDATE $tableName SET `customer_id` = " . $savedCustomer->getId() . ",customer_is_guest = 0,customer_group_id =" . $savedCustomer->getGroupId() . " WHERE $tableName.`entity_id` IN (" . $gustOrderId . ")";

                $this->resourceConnection->getConnection()->query($sql);

                $tableName = $this->getTableName('sales_order_grid');

                $sql = "UPDATE $tableName SET `customer_id` = " . $savedCustomer->getId() . ",customer_group=" . $savedCustomer->getGroupId() . " WHERE $tableName.`entity_id` IN (" . $gustOrderId . ")";

                $this->resourceConnection->getConnection()->query($sql);

            }

            return $this;

        } catch (\Exception $e) {

            $this->logger->critical($e->getMessage());

        }

    }

    public function getTablename($tableName)

    {

        $connection = $this->resourceConnection->getConnection();

        $tableName = $connection->getTableName($tableName);

        return $tableName;

    }

}

That’s It.

Wrap Up:

Expectantly, all are able to implement the above illustration without any difficulties. To automate this functionality without following the complicated codes integrate the Magento 2 Assign Order to Customer extension.

In case of any errors you come through in between the implementation then let me know in the comment section below I will solve them out there. 

Share the illustration with your Magento Developer Friends.

Happy Reading.

Click to rate this post!
[Total: 4 Average: 5]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate 🎖️ Certified Magento Developer👨‍💻. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.🏏

Recent Posts

What are Net Sales? How to Calculate Your Net Sales?

In the world of business, understanding financial metrics is crucial for making informed decisions and…

2 days ago

Magento 2 Extensions Digest April 2024 (New Release & Updates)

Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…

2 days ago

The ABCs of Geofencing: Definition, Features and Uses

In this era, businesses are always on the lookout for ways to engage with their…

3 days ago

How to Delete Product Variant in a Shopify Remix App using GraphQL Mutations?

Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…

4 days ago

6 Innovative Tools Revolutionizing E-Commerce Operations

E-commerce has transformed the way consumers shop for products and services and interact with businesses.…

6 days ago

How Upcoming Cookie Changes Will Affect Your E-commerce Website?

The e-commerce world is constantly in flux. New tech and strategies emerge daily to help…

6 days ago