Categories: How To

How to Setup Google Analytics in Magento with Google Tag Manager

Google tag manager is a tag management system that creates tags and passes user interaction data. Rather than setting up everything manually, Google Tag Manager gives space to create complex & custom tags, saves time, adds scalability to your site implementation and most importantly, it’s easy to use. Implementing Google Analytics through Google Tag Manager needs much efforts but ultimately it simplifies future upgrades & enhancements as modifications can be done through GTM rather than each page of your website. Here, we will show you how to setup Google Analytics in Magento with Google Tag Manager.

Steps to setup Google Tag Manager in Magento:

    1. First of go to Google Tag Manager, add your account if already not created. Here you can find your container ID, click on it and you can find two codes to paste in your website pages.
    2. Copy the code and paste both of them exactly below body tag of your website. Here you will find instructions to put both the code at different places but it’s not working properly in Magento. So follow our instruction as above.

Setup Google Analytics:
The below steps are same as inserting analytics code into site which will start tracking page views and other information.

      1. Go to Google Tag Manage, Open “Overview” tab and click “Add New Tag”.
      2. Name the tag with “Universal Analytics” and click “Choose a tag type to begin setup”.
      3. Select tag type as “Universal Analytics” from the options.
      4. Go to Google Analytics and get tracking ID from admin under “Tracking Info” and copy it. If you haven’t created Google Analytics account, create an account first using this guide.
      5. Insert copied Tracking ID into “Tracking ID” field. Select “Page View” under “Track Type” and then click “Advanced Settings” and select “Once Per Page” under “Tag firing options”.
      6. Select “Triggering” section below and click “Choose a trigger to make this tag fire”.
      7. Select “All Pages”, save the tag and click “Publish” from the admin.
      8. To track live users on your website in Google Analytics, go to your website from another browser, click on some links. Open Real time –> Overview in Google Analytics. Here you can see total number of live users with other related details.

Set up Ecommerce Transactions:

      1. Go to GTM, open “Variables” tab. Under “User-Defined” variables and click “New”. Create new variable, name it “currencyCode”. Now click “Choose a variable type to begin setup”.
      2. Select variable type as Data Layer Variable.
      3. Enter “currencyCode” as “Data Layer Variable Name”. Keep the Data Layer version selected as version 2 and click “save”.
      4. Now go to “Overview” tab and click “Add a new tag”. Enter tag name as “Order” and click “Choose a tag type to begin setup”. Click “Universal Analytics” under tag type. Insert Google Analytics tracking ID just as we did before. Here, select “Transaction” as track type. Now click “More settings” –> “Fields to set” –> “Add Field” and enter Field Name “currencyCode” and Value as {{currencyCode}}.
      5. Now go to triggering section and click “Choose a trigger to make this tag fire”. Click + sign from the top right corner. Enter trigger name as “Order” and click “Choose a trigger type to begin setup”. From “Choose trigger type”, select “DOM Ready”. Now select “Some DOM Ready Events” under “This trigger fires on” and select values “Page URL”, “Contains” respectively and insert “checkout/onepage/success” into the third field which is Magento default success order page. If you have custom URL for success page, add that path. Save the trigger. After saving the trigger you will see the summary of creating the tag. Click “Save” and then “Publish”.
      6. Now go to Google Analytics and click on Ecommerce Settings in admin panel. Enable Ecommerce, click “Next Step” and Submit.
      7. Now put the following code in your success.phtml file available at \app\design\frontend\[your_theme_package]\template\checkout\success.phtml
        <!--?php $order = Mage::getModel('sales/order')->loadByIncrementId($this->getOrderId());
        $items = $order->getAllVisibleItems();
        $products = array();
        
        foreach ($items as $item) {
         $price = $item->getPrice();
         $product = $item->getProduct();
         $prd = Mage::getModel('catalog/product')->load($item['product_id']);
         $cat_name='';
         $cats = $prd->getCategoryIds();
         foreach ($cats as $category_id) 
         {
           $_cat = Mage::getModel('catalog/category')->setStoreId(Mage::app()->getStore()->getId())->load($category_id);
           $cat_name.= $_cat->getName().' ';             
         }
         
         $products[] = array(
          'sku'      => $item->getSku(),
          'name'     => $item->getName(),
          'category' => $cat_name,
          'price'    => round($price, 2),
          'quantity' => (int)$item->getQtyOrdered()
         );
        }
        
        $data = array(
         'transactionId'          => $order->getIncrementId(),
         'transactionTotal'       => max(round($order->getGrandTotal(), 2), 0),
         'transactionTax'         => round($order->getTaxAmount(), 2),
         'transactionShipping'    => round($order->getShippingAmount(), 2),
         'currencyCode'           => $order->getOrderCurrencyCode(),
         'transactionProducts'    => $products
        );
        
        $data = json_encode($data);
        ?-->
        <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%3E%0AdataLayer%20%3D%20%5B%20%3C%3Fphp%20echo%20%24data%3B%20%3F%3E%20%5D%3B%0A%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="<script>" title="<script>">
        
      8. After setting up as above, you can track Ecommerce Transactions in Google Analytics at Conversions –> Ecommerce –> Transactions. To test Ecommerce Transactions, place some test orders from your store. Check back Google Analytics at above path and you can see the Ecommerce Transactions data. Note that Ecommerce transactions are not displayed real time. Usually it takes up to 24 Hours to refresh the transaction data so just check back if you can’t find transaction.

Hope this step by step guide has enough helped you to setup Google Tag Manager in Magento. Still, if you find any queries or you stuck somewhere, let me know, I’ll be glad to help you. Send your feedback through commenting.

Even you can Download PDF of this guide to save for later use.

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

How to Integrate ChatGPT with Laravel Application?

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

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

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

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

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

5 days ago

6 Innovative Tools Revolutionizing E-Commerce Operations

E-commerce has transformed the way consumers shop for products and services and interact with businesses.…

1 week ago