Reputation: 110
I am trying to get the User-ID feature to work within Google Analytics. In order to do this, I have to pass a PHP variable to Google Analytics using JavaScript.
I have attempted to do this by echoing all of the Javascript in a PHP script.
Here is that script:
<?php
if (isset($username)) {
echo "\n";
echo "<script type='text/javascript'>\n";
echo "(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');\n";
echo "ga('create', 'UA-********-1', 'auto');\n";
echo "ga('set', 'userID', '" . $username . "');\n";
echo "ga('send', 'pageview');\n";
echo "</script>\n";
} else {
echo "\n";
echo "<script type='text/javascript'>\n";
echo "(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');\n";
echo "ga('create', 'UA-********-1', 'auto');\n";
echo "ga('send', 'pageview');\n";
echo "</script>\n";
}
?>
Unfortunately, it doesn't work. Can anybody tell me what I'm doing wrong?
UPDATE 2015-12-03
I have decided to use a more direct method to test whether or not the user is logged-in, and also, I've combined the different echoes into one for each leg of the conditional statement:
<?php
if (login_check($mysqli) == true) {
echo "<!-- Google Analytics with userId -->
<script>
window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
ga('create', 'UA-XXXXX-Y', 'auto');
ga('set', 'userId', '" . $_SESSION['user_id'] . "');
ga('send', 'pageview');
</script>
<script async src='//www.google-analytics.com/analytics.js'></script>
<!-- End Google Analytics -->";
} else {
echo "<!-- Google Analytics with pageview only -->
<script>
window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
ga('create', 'UA-XXXXX-Y', 'auto');
ga('set', 'userId', '" . 'anonymous' . "');
ga('send', 'pageview');
</script>
<script async src='//www.google-analytics.com/analytics.js'></script>
<!-- End Google Analytics -->";
}
?>
This new snippet works. Note though that I had to set userId
in order for the code in the else statement to work. It must be the case that you have to set userId
if you enable user tracking in Google Analytics. I have not verified that yet, but it does seem like a reasonable inference.
Upvotes: 0
Views: 2027
Reputation: 8907
The name for the User ID parameter that you are using is not correct. It should be userId
(camel case), but you are using userID
. Also, make sure you have the User ID feature enabled from the GA interface.
Upvotes: 1