I like to ask where I should place this code snippet:

  fbq('track', 'Purchase', {
    value: 1,
    currency: 'SEK',

I have added the normal facebook tracking code into the head for all pages. But I like to add this specific codesnippet to after the order is completed/success. And what variable name should I use for the value?

Which file, and what is the variable name? This is for Magento 2.3

Many thanks!


You are going to need to either use a module or create one of your own for this:

If you choose to create a module, after you set up the base module. You can add checkout_onepage_success.xml file under \CompanyName\ModuleName\view\frontend\layout with the following content:

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
        <referenceBlock name="order.success.additional.info">
            <block class="CompanyName\ModuleName\Block\Checkout\Success\Facebookpixel" name="modulename.checkout.success.facebookpixel" template="checkout/success/facebookpixel.phtml"

Then add facebookpixel.phtml under \CompanyName\ModuleName\view\frontend\templates\checkout:

$order = $this->getOrder();
$pixelValue = number_format($order->getBaseGrandTotal(),2);
$pixelCurrency = $order->getOrderCurrencyCode();

fbq('track', 'Purchase', {
  value: <?php echo $pixelValue;?>,
  currency: '<?php echo $pixelCurrency;?>'

Then add success.php file under \CompanyName\ModuleName\Block\Checkout\Success:

// @codingStandardsIgnoreFile

namespace CompanyName\ModuleName\Block\Checkout\Success;

 * FB Page Block
class Facebookpixel extends \Magento\Framework\View\Element\Template
    /** @var \Magento\Sales\Model\OrderFactory */
    protected $_salesFactory;

    /** @var \Magento\Checkout\Model\Session */
    protected $_checkoutSession;

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

     * Retrieve current order
     * @return \Magento\Sales\Model\Order\OrderFactory
    public function getOrder()
        $orderId = $this->_checkoutSession->getLastOrderId();
        return $this->_salesFactory->load($orderId);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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