Last active
October 9, 2024 00:33
-
-
Save chrisblakley/2f5322b324ac59d19ecb to your computer and use it in GitHub Desktop.
Google Page Speed tracking
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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