Implementing Google Tag Manager with Discourse

Like with any site Google Tag manager is just another method to use for Google analytics. If all you are using is analytics then there’s no real point in tag manager. But if you plan on using all the features of tag manager then go ahead. It’s quite easy to deploy from memory.

1 Like

I moved to GTM approx. 2 month ago. Placed GTM code in Header.
Now I noticed that pageview and bounce rate is calculated differently then it was before thru Google Analytics tracking code

bounce rate goes up significantly

pageviews goes down significantly

Any ideas why it’s happened?

1 Like

How have you implementer it? Not looked at how route changes work on doscourse, but simple header / footer code might not push appropriate page view events to GA.

Your GA stats indicate that page views are not getting pushed, which increases your bounce rates.

You added it in the </head> section of a site customization? You can watch network requests in the developer console of your browser to see if/when requests to gtm are being made.

2 Likes

@shri @neil i put in header http://localhost/admin/customize/css_html/2/header as per GTM instructions js code should be just after body tag.

what is your suggestions how to integrate GTM with discourse (ember.js)

I have little experience with discourse, but knowing frontend apps and how things worked in Meteor etc, GTM needs to be called during route changes, when users navigate.

Give me a few days to look at it. I’m barely on day 3 or 4 with this beast. :slight_smile:

3 Likes

FYI … quick one for you to look at.

Take a look at the DFP plugin and see if you can get a clue from there. The refresh is called properly when the route changes.

  refreshAd: function() {
    var ad = ads[this.get('placement')];
    if (!ad) { return; }

    if (this.get('loadedGoogletag')) {
      googletag.cmd.push(function() {
        googletag.pubads().refresh([ad]);
      });
    }
  }.observes('refreshOnChange'),

https://github.com/discourse/discourse-google-dfp/blob/master/assets/javascripts/discourse/components/google-dfp-ad.js.es6

1 Like

You’re saying that isn’t happening? I’ve been given this screenshot that suggests it is:

That site also has the discourse-adplugin installed, which uses the googletag api, so maybe the DFP api is doing the work for gtm analytics.

If that’s the case, then the discourse-adplugin could also become the google tag manager analytics plugin.

2 Likes

@shri @neil googletag api in DFP is Google Publisher Tag api but not google tag manager. I’m not quite sure how DFP google publisher tag api can influence on google tag manager.

Also I turn on GTM debug mode.

  1. open discourse
  2. click topic
  3. go to home page
  4. click another topic

Only 1 pageview is triggered, however I was expecting 4 pageviews per above.

And here Adding Google Analytics Tracking - Cookbook - Ember Guides outlined need to add code to router

@neil - I have yet to look at GTM, was just giving a broad hint. I’d assume that the header / footer are not reloaded on a frontend ember app, so the GTM would not be called on every pageload.

I’ll look at this over the weekend, it is on my list of things to do as we need to add quantcast and a facebook audience pixel to the site.

@neil / @polusok

Quick way to figure out if GTM is being triggered would be to put a console log right before or after the call to GTM. Not saying just adding the code to the footer is not correct, just suggesting that it may be better to log and figure out which approach works.

I created this snippet in the footer section of the Admin > Customise

<script>
    // console.log("Getting URL");
    Ember.Application.initializer({
        name: 'googleTagManager',

        initialize: function (container, application) {
        var router = container.lookup('router:main');

            router.on('didTransition', function () {
                console.log("Did Transition" );
            });
        }
    });
</script>

And it seemed to log every route transition.

This is based on the ember gtm implementation found here.

https://gist.github.com/pwfisher/5fd09ec2ccab253008f9

Again, I’ve not spent any significant time studying how things really work in Discourse, but will look further to see how this piece of code works.

https://github.com/discourse/discourse/blob/be3a5a56ccc284b352aa65080fc6b955f73cc72a/app/assets/javascripts/discourse/initializers/show-footer.js.es6

2 Likes

@neil / @polusok

**Should warn you - this is hacky and might just break everything. :slight_smile: **

Javascript problems forced me to learn this:

I’ve had some success implementing GTM analytics for now.

  1. Open your analytics account and go over to the real time > content view. This should preferably be done on a development site to avoid noise from regular visitors.
  2. Configure your GTM TAG as follows:
  • Product - Google Analytics
  • Type: Universal Analytics
  • Configure Tag: Tracking ID / enable disable whatever else you want, TrackType: Pageview. I also enable Debug View to get some logs in the JS console.
  • Fire On: We’ll select a custom trigger here after completing step 3
  1. Configure a trigger as follows:
  • Event - Custom Event. I’ve called it ‘DiscourseRoute’
  • Fire On - Event Name (I’ve named it ‘PageView’ to keep things simple.
  1. Go back to the tag and select the firing trigger to be the event you configured (DiscourseRoute)

In your admin -> customise -> CSS / HTML -> Header add the call to GTM

<!-- Google Tag Manager -->
<noscript><iframe src="//www.googletagmanager.com/ns.html?id=GTM-ND3497"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','_YOUR_CONTAINERID_**');</script>
<!-- End Google Tag Manager -->

Note that this is called ‘dataLayer’ (case sensitive…)

In your </body> section add this.

<script>
    // console.log("Getting URL");
    Ember.Application.initializer({
        name: 'googleTagManager',

        initialize: function (container, application) {
        var router = container.lookup('router:main');
            console.log('Firing Custom Pageview');
            router.on('didTransition', function () {
                    dataLayer.push({
                         'event': 'PageView'
                    });

            });
        }
    });
</script>

Note that the event is a custom event called ‘PageView’.

Save / force refresh and inspect your JS console on your discourse page. You should see the event being fire (console log output) followed by a bunch of debug output from GTM showing that it converted the custom event into a analytics pageview and the variables being passed back to analytics.

The analytics real time console should also show the pageviews being sent over.

3 Likes

Thank you very much, however I will have chance to try only on weekends

This is telling me that we should add google tag manager analytics support with site settings like we do with universal tracking. Your code is basically repeating our page-tracking.js. I’m confused why anyone thought it was working. I setup my own gtm account, set it up, and clearly it doesn’t send the events without code like you’ve written.

4 Likes

GTM is widely spread and I also think it should be supported as default

1 Like

Thank you for the pointer. I had not found that and was too lazy to look. Will take a look a little bit later and see if I am doing this correctly.

Yes, I am surprised to that anyone thought it was working - but high bounce rates are always a good clue. :slight_smile:

I need to check and see if it works well with Quantcast and also Facebook Audience pixels. Will play around with those today.

1 Like

I think I have it working in a branch:

https://github.com/discourse/discourse/commit/8074d3bed9c4cfaee71e0ac88e4e614e0a59c14f

The tricky part is setting up GTM to pass along the events to UA. UA is getting the page views, but they’re all at the root url. I’ve defined our own events (page.title and page.url), but GTM also has an automatic history listener (not sure it includes page title, so we might want to keep the custom events). Either way, I don’t have the GTM setup correct yet. I’ll keep playing around in the baffling GTM interface.

4 Likes

Everything seems to be working. I wrote up a howto, so tag manager experts please review. :grin:

7 Likes

awesome, I need to update to latest version to try, it will take a bit and then I will check

Did everything as per instructions, working like a charm! Thank you very much!

However, need to wait 1 or 2 days to see final statistics and results. I will let you.

UPD: Everything is fine! You can use solution.

6 Likes