javascriptwordpressgoogle-analyticsfacebook-instant-articles

How to properly integrate Google Analytics in FB Instant Articles?


I am running Instant Articles For WP on my Wordpress site, at the moment all the traffic coming from Instant Articles isn't registering in Google Analytics.

I did a little research and found that facebook allows the additional of 3rd party tracking codes.

I'm using the new gTag.js instead of the old method.

This is code is placed before </head>

<!-- Global Site Tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-MY-ID"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'UA-MY-ID');
</script>

And this is the code in Instant Articles Wordpress plugin, in the "Embed Custom Code" section.

<figure class="op-tracker">
    <iframe>

        <script async src="https://www.googletagmanager.com/gtag/js?id=UA-MY-ID"></script>
        <script>
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());

            gtag('create', 'UA-MY-ID', 'auto');
            gtag('require', 'displayfeatures');
            gtag('set', 'campaignSource', 'Facebook');
            gtag('set', 'campaignMedium', 'Instant Article');
            gtag('set', 'page_title', 'Instant Articles: '+ia_document.title);
            gtag('send', 'pageview');

            gtag('config', 'UA-MY-ID');
        </script>

    </iframe>
</figure>

Yet, I still don't see any campaigns being created in my analytics dashboard. I don't see the traffic coming from Instant Articles at all.


Solution

  • The issue has been fixed. I removed the HTML tags and fixed the parameters of ga to the following

    <script>
      (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
      (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
      m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
      })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
    
      ga('create', 'UA-MY-ID', 'auto');
      ga('set', 'campaignSource', 'Facebook');
      ga('set', 'campaignMedium', 'Facebook Instant Articles');
      ga('set', 'referrer', ia_document.referrer);
      ga('send', 'pageview');
    
    </script>