Magento 2: get order id on success page
-
15-04-2021 - |
سؤال
I'm trying to put the conversion event snippet into my success page, but I dont know how do I get the order_id to pass with.
My code is:
gtag('event', 'conversion', {
'send_to': '...',
'transaction_id': '<?= $orderId ?>'
});
But how do I define the $orderId
on success page's head tag?
المحلول
If you have custom block then, just inject this below code in your block file :
Construct Method
protected $checkoutSessionFactory;
public function __construct(
\Magento\Checkout\Model\SessionFactory $checkoutSessionFactory
){
$this->checkoutSessionFactory = $checkoutSessionFactory;
}
public function checkoutSessionObj()
{
return $this->checkoutSessionFactory->create();
}
After that, you can use this below code in your phtml file.
$orderObj = $block->checkoutSessionObj()->getLastRealOrder();
echo $orderObj->getEntityId(); //Entity Id
echo $orderObj->getIncrementId(); //Increment Id
Object Manager Method :
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$orderObj = $objectManager->create('Magento\Checkout\Model\Session')->getLastRealOrder();
echo $orderObj->getEntityId(); //Entity Id
echo $orderObj->getIncrementId(); //Increment Id
Note : Don't use object manager directly
لا تنتمي إلى magento.stackexchange