Link to home
Start Free TrialLog in
Avatar of Sarah Ward
Sarah WardFlag for United States of America

asked on

Google Analytics / JavaScript: Get Client ID

I'm working in WordPress and I have this block of JS code on my page. I'm trying to write the Google Analytic Client ID in the console, however, I'm getting the following console error:

Uncaught ReferenceError: ga is not defined


<script>

    ga('create', 'UA-123456789-1', 'auto');
    ga('send', 'pageview');
    
    ga(function(tracker) {
      console.log(tracker.get('clientId'));
      /* Your other code here */
    });

</script>

Open in new window


What am I missing?  Any help would be appreciated.  Thanks!
Avatar of Michel Plungjan
Michel Plungjan
Flag of Denmark image

1. You need the ga script before the code above
2. You need to check that ga is not rewritten to for example __gaTracker viz: https://wordpress.org/support/topic/why-__gatracker-instead-of-ga/

You can try this:

window.addEventListener("load",function() {
  let ga = ga || __gaTracker;
  if (ga) {
    ga('create', 'UA-123456789-1', 'auto');
    ga('send', 'pageview');
    
    ga(function(tracker) {
      console.log(tracker.get('clientId'));
      /* Your other code here */
    });
  }
  else { console.log("We need some other means to get to ga"); }
});

Open in new window

Avatar of Sarah Ward

ASKER

Hi Michel - Thanks for helping me. It's greatly appreciated.  

I've added your code to the footer of my page, but I'm still getting the same error.  

FYI:  I'm using a plugin in WordPress called 'Google Site Kit'.   Could I be missing a script or something that the Google Site Kit plugin doesn't add to my page in order to get this working?  Here's a screenshot of my error.

User generated image
User generated image
ASKER CERTIFIED SOLUTION
Avatar of Michel Plungjan
Michel Plungjan
Flag of Denmark image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial