A Not So $h!tty Google-Analytics JavaScript Code

Posted at


There are some new stuff running at Google,
making Analytics better then ever,
however, the javascript code raised a lot of eyebrows due to its complexity,

oh and the help-page for the user-visitors contains some UTF-8 weird stuff added by mistake to the code..

here is a "not so $h!tty stuff" that will not @#$ up your page, its broken down to 3 <script>
tags, that should be placed in the very end of the document, just before the closing body tag (</body>).

as a bonus there is an example on how to use the unique user-id featured (essentially everything new is here you can use the Analytics)

first, locate this in your very top of the page, just before the doctype area

  if(! isset($_SESSION['uniqueID'])){
    $_SESSION['uniqueID'] = uniqid();

  setlocale(LC_ALL, 'he_IL.UTF-8');
  //setlocale(LC_CTYPE, 'en_US.UTF-8');
  //header('Content-Type: text/plain; charset=UTF-8'); //header('Content-Type: text/plain; charset=windows-1255');
<!DOCTYPE html>
<html lang="en-US">

and this, at the end of the document

window["GoogleAnalyticsObject"] = "ga";
window["ga"] = window["ga"] || function(){
window["ga"].l = 1 * new Date();

window["ga"].q = window["ga"].q || [];
<script src="https://www.google-analytics.com/analytics.js"></script>
window["ga"]("create", "UA-THE_CODE_FROM_GOOGLE-1", "THE_DETAIL_FROM_GOOGLE");
window["ga"]("require", "displayfeatures");
window["ga"]("require", "linkid", "linkid.js");
window["ga"]("set", "&uid", "<?php print($_SESSION['uniqueID']); ?>");
window["ga"]("send", "pageview");


extract your values ("UA-THE_CODE_FROM_GOOGLE-1" and "THE_DETAIL_FROM_GOOGLE") from your original Google-Analytics code-snippet,
your visitors will have an additional cookie, maintaining their identity on your website, this is 100% maintained by PHP, you can also use any PHP variable such as wordpress login name, or even a variation of the guest IP or any other detail you would like to track, and put it instead of the session-id, but, this is the easiest way.

while processing the code I've came across some weird UTF-8 characters that were breaking my page,
this was due to I was copying&pasting it from Google-support, into my page,
solution was using Notepad++ to convert the PHP file to UTF-8, then the symbols were visible, and I've just deleted them, saved and uploaded the PHP file as binary through FTP.