Google Analytics Async Event Tracking

Trying to figure out how to get event tracking working with the new async (analytics.js) code was a pain. Googles documentation for anything to do with analytics is always confusing.

<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’,’//www.google-analytics.com/analytics.js’,’ga’);

ga(‘create’, ‘UA-XXX-X’, ‘example.com’);
ga(‘send’, ‘pageview’);

//here is the code that actually worked. You put it in the script area with the rest of your analytics code right at the bottom.
ga(‘send’, {
  ‘hitType’: ‘event’,          // Required.
  ‘eventCategory’: ‘live-events’,   // Required.
  ‘eventAction’: ‘click’,      // Required.
  ‘eventLabel’: ‘live-events’,
  ‘eventValue’: 1
});

</script>

Then you make sure the link that you are clicking on has the correct id, in this case id=”live-events”

<a id=”live-events” href=”<?php the_field(‘sidebar_cta_link’, 480); ?>” class=”sidebar-ad”>
<img src=”<?php the_field(‘sidebar_cta_image’, 480); ?>”>
</a>

I used the Advanced Custom Fields plugin to add the ability to change the event name along with the image. If you just use a normal text field entry type with the convert HTML to tags selected then it works.

<?php the_field(‘header_google_tracking_code’, 480); ?>
<?php the_field(‘sidebar_google_tracking_code’, 480); ?>
<?php the_field(‘footer_google_tracking_code’, 480); ?>

 

This is the link to the page that has the actual code.

https://developers.google.com/analytics/devguides/collection/analyticsjs/events

Leave a Reply