4

Currently trying to add some order tracking to our success page, however we need to be able to access information like the value of the order, the number of items ordered, item SKUs etc.

Are there any simple code snippets to access this information or does it all have to be passed manually?

3 Answers 3

4

You can just add below code inside success.phtml file,and you can fetch required data using below code,

 <?php $objectManager =  \Magento\Framework\App\ObjectManager::getInstance();
          $orderData = $objectManager->create('Magento\Sales\Model\Order')->loadByIncrementId($block->getOrderId());
          echo "<pre>";print_r($orderData->getData());
         //echo $orderData->getData('shipping_description'); //shipping_description
    ?>
4
  • 2
    This is not the recommended way of doing it in magento 2. Object manager should not be used.
    – Paras Sood
    Apr 18, 2017 at 6:40
  • This gives blank page in 2.1.8
    – akgola
    Sep 15, 2017 at 10:52
  • How to get a country_code from order data? May 4, 2018 at 9:40
  • @ParasSood What's the recommended method to do it? Sep 22, 2018 at 17:43
5

To get the order details in the success.phtml , you can use the below code :

protected $_checkoutSession;

public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Sales\Model\Order $salesOrderFactory,
        \Magento\Checkout\Model\Session $checkoutSession,
        array $data = []
    ) {
        $this->_checkoutSession = $checkoutSession;
        parent::__construct($context, $data);
    }

/**
* Retrieve current order
*
* @return \Magento\Sales\Model\Order
*/
public function getOrder()
{
   $orderId = $this->_checkoutSession->getLastOrderId();
   $order   = $this->_salesFactory->load($orderId);
   return $order->getData(); // you can access various order details from here. 
}
2
  • Thanks for your answer. My apologies, but I'm still not too familiar with the frameworks Magento uses. Would the above code be usable on success.phtml or does it need to be done elsewhere? Apr 13, 2016 at 10:35
  • 2
    You need to override the block vendor/magento/module-checkout/Block/Onepage/Success.php and define the function getOrder in my answer. then you can use the function in success.phtml by $block->getOrder() Apr 13, 2016 at 10:43
2

From Manashvi birla code, I used this :

$order = $this->_checkoutSession->getLastRealOrder();

in place of this :

$orderId = $this->_checkoutSession->getLastOrderId();
$order   = $this->_salesFactory->load($orderId);
2
  • I tried Manashvi's answer and it gave me an error. But when I fixed it with this, it worked for me. Mar 27, 2018 at 11:12
  • Yes it worked for me too!
    – Max Leps
    Apr 13, 2021 at 13:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.