Magento Tutorials

How to Add Tracking Number to the Current Order Shipment in Magento 2

In this Magento Tutorial blog, I will help you How to Add Tracking Number to the Current Order Shipment in Magento 2. You can also learn the stepwise method of How to add Order tracking ID link in Shipping Email of Magento 2. Let’s get started with today’s topic.

Quick Intro:

Basically, all the E-commerce stores provide their customers to track their orders. In any case, the shipment is not reached at a time or delayed for some reason then the store merchants as well as customers can track their parcel with the help of tracking numbers. By implementing this method the Magento 2 store admin can resolve the problems that their store customer face with the shipment tracking. This functionality will help in upgrading the customer experience of your Magento 2 store.

Implementing this facility helps the store merchants to gain the trust of their customers because if the customer has ordered from an online store the very first time then the Tracking Number will solve their worries by checking where the shipment is reached and how much time it will consume to deliver to you successfully. With the implementation of the following steps, you can strengthen the user experience of your online store. 

Steps to Add Tracking Number to the Current Order Shipment in Magento 2:

Step 1: Create one file in your Magento root directory and paste the below code.

<?php
use Magento\Framework\AppInterface;
try {
    require_once __DIR__ . '/app/bootstrap.php';
} catch (\Exception $e) {
    echo 'Autoload error: ' . $e->getMessage();
    exit(1);
}
try {
    $bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
    $objectManager = $bootstrap->getObjectManager();
    $appState = $objectManager->get('\Magento\Framework\App\State');
    $appState->setAreaCode('frontend');

    $order = $objectManager->create('Magento\Sales\Model\Order')->loadByAttribute('increment_id', '000000009');

    if (!$order->canShip()) {
        throw new \Magento\Framework\Exception\LocalizedException(
            __('You can\'t create an shipment.')
        );
    }

    $orderconvert = $objectManager->create('Magento\Sales\Model\Convert\Order');
    $shipment = $orderconvert->toShipment($order);

    foreach ($order->getAllItems() as $orderItem) {
        if (!$orderItem->getQtyToShip() || $orderItem->getIsVirtual()) {
            continue;
        }

        $qtyShipped = $orderItem->getQtyToShip();

        $shipmentitem = $orderconvert->itemToShipmentItem($orderItem)->setQty($qtyShipped);
        $shipment->addItem($shipmentitem);
    }

    $shipment->register();
    $trackingdata = array(
        'carrier_code' => 'fedex',
        'title' => 'Federal Express',
        'number' => 'FED0123',
    );

    $shipment->getOrder()->setIsInProcess(true);
    $track = $objectManager->create('Magento\Sales\Model\Order\Shipment\TrackFactory')->create()->addData($trackingdata);
    $shipment->addTrack($track)->save();
    $shipment->save();
    $shipment->getOrder()->save();
    $objectManager->create('Magento\Shipping\Model\ShipmentNotifier')->notify($shipment);
    $shipment->save();
    echo "Tracking Number to the Current Order Shipment in successfully added.";
}
catch (\Exception $e) {
    echo $e->getMessage();
}

You are done with it.

Conclusion:

Hopefully, you have implemented the above solution to Add Tracking Number to the Current Order Shipment in Magento 2. In case of any trouble let me know down in the comment section. 

Share the article with your Magento Friends.

Happy Reading!

Click to rate this post!
[Total: 6 Average: 4.3]
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

Magento 2: Add Quantity Increment and Decrement on Category Page

Hello Magento Friends, In this blog, we will discuss about adding quantity increment and decrement…

12 hours ago

How to Integrate ChatGPT with Laravel Application?

In this guide, we'll explore how to integrate ChatGPT, an AI-powered chatbot, with a Laravel…

4 days ago

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…

6 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…

6 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…

7 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…

1 week ago