Skip to content

Instantly share code, notes, and snippets.

@chrisblakley
Last active February 11, 2016 23:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisblakley/2f5322b324ac59d19ecb to your computer and use it in GitHub Desktop.
Save chrisblakley/2f5322b324ac59d19ecb to your computer and use it in GitHub Desktop.
Google Page Speed tracking
function gaParseCookie() {
if (isset($_COOKIE['_ga'])) {
list($version,$domainDepth, $cid1, $cid2) = explode('.', $_COOKIE["_ga"], 4);
$contents = array('version' => $version, 'domainDepth' => $domainDepth, 'cid' => $cid1 . '.' . $cid2);
$cid = $contents['cid'];
} else {
$cid = gaGenerateUUID();
}
return $cid;
}
function gaGenerateUUID() {
return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand(0, 0xffff), mt_rand(0, 0xffff), //32 bits for "time_low"
mt_rand(0, 0xffff), //16 bits for "time_mid"
mt_rand(0, 0x0fff) | 0x4000, //16 bits for "time_hi_and_version", Four most significant bits holds version number 4
mt_rand(0, 0x3fff) | 0x8000, //16 bits, 8 bits for "clk_seq_hi_res", 8 bits for "clk_seq_low", Two most significant bits holds zero and one for variant DCE1.1
mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff) //48 bits for "node"
);
}
function gaSendData($data) {
$getString = 'https://ssl.google-analytics.com/collect';
$getString .= '?payload_data&';
$getString .= http_build_query($data);
$result = wp_remote_get($getString);
return $result;
}
if ( strpos($_SERVER['HTTP_USER_AGENT'], 'Google Page Speed') !== false ) {
$protocol = stripos($_SERVER['SERVER_PROTOCOL'], 'https') === true ? 'https://' : 'http://';
$currentURL = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
if ( strpos($currentURL, ".js") !== false ) {
exit();
} else {
global $post;
$currentTitle = get_the_title($post->ID); //This example uses WordPress to get the page title
}
$data = array(
'v' => 1,
'tid' => UA-0000000-1, //Add your Google Analytics account number here!
'cid' => gaParseCookie(),
't' => 'event',
'ec' => 'Google Page Speed', //Category
'ea' => $currentURL, //Action
'el' => $currentTitle //Label
);
gaSendData($data);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment