X
    Categories: Knowledgebase

How to add tracking url in shipment email for customer in magento 2

You can copy vendor/magento/module-sales/view/frontend/email/shipment_new.html to your theme and edit line 56 (here you can change block for which display track information), you can change it like this

{{
    block class='Your_Package\Your_Module\Block\Sales\Email\Shipment\Track' 
    area='frontend' 
    template='Magento_Sales::email/shipment/track.phtml' 
    shipment=$shipment order=$order
}}

After that you need create this block

<?php

namespace Your_PackageYour_ModuleBlockSalesEmailShipment;

use MagentoFrameworkViewElementTemplate;

class Track extends Template
{
    /**
     * @var MagentoShippingModelOrderTrackFactory
     */
    protected $_trackFactory;

    /**
     * Constructor
     *
     * @param MagentoShippingModelOrderTrackFactory $trackFactory
     * @param TemplateContext $context
     * @param array $data
     */
    public function __construct(
        MagentoShippingModelOrderTrackFactory $trackFactory,
        TemplateContext $context,
        array $data = [])
    {
        $this->_trackFactory = $trackFactory;
        parent::__construct($context, $data);
    }

    /**
     * Retrieve tracking by tracking entity id
     *
     * @return array
     */
    public function getTrackingInfoByTrackId($trackId)
    {
        /** @var MagentoShippingModelOrderTrack $track */
        $track = $this->_trackFactory->create()->load($trackId);
        if ($track->getEntityId()) {
            $result = $track->getNumberDetail();
        } else {
            $result = null;
        }
        return $result;
    }
}

Then copy template vendor/magento/module-sales/view/frontend/templates/email/shipment/track.phtml to your theme and change line 25 to

<td>
    <?php 
        $trackingInfo = $block->getTrackingInfoByTrackId($_item->getEntityId());
    ?>
    <?php if ($trackingInfo->getUrl()): ?>
        <a href="<?= $block->escapeHtml($trackingInfo->getUrl()) ?>"
           >

You also may need copy vendor/magento/module-sales/view/frontend/email/shipment_new_guest.html the same like shipment_new.html

Thank for reading this post, Hope it helps.

Kien Wiliam: Magento Ecommerce Developer