您需要查看Google Analytics(分析)server-side measurement protocol。
這是一個PHP實現,我已經成功,但它可能是矯枉過正的用例(但至少它是一個參考)。 Here is the full code,但我已經簡化了這篇文章。
//Handle the parsing of the _ga cookie or setting it to a unique identifier
function ga_parse_cookie(){
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 = ga_generate_UUID();
}
return $cid;
}
//Generate UUID v4 function (needed to generate a CID when one isn't available)
function ga_generate_UUID(){
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"
);
}
//Send Data to Google Analytics
//https://developers.google.com/analytics/devguides/collection/protocol/v1/devguide#event
function ga_send_data($data){
$getString = 'https://ssl.google-analytics.com/collect';
$getString .= '?payload_data&';
$getString .= http_build_query($data);
$result = wp_remote_get($getString);
return $result;
}
//Send Event Function for Server-Side Google Analytics
function ga_send_event($category=null, $action=null, $label=null, $value=null, $ni=1){
//GA Parameter Guide: https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters?hl=en
//GA Hit Builder: https://ga-dev-tools.appspot.com/hit-builder/
$data = array(
'v' => 1,
'tid' => 'UA-XXXXXX-Y', //***** Replace with your tracking ID!
'cid' => ga_parse_cookie(),
't' => 'event',
'ec' => $category, //Category (Required)
'ea' => $action, //Action (Required)
'el' => $label, //Label
'ev' => $value, //Value
'ni' => $ni, //Non-Interaction
'dh' => 'gearside.com', //Document Hostname
'dp' => '/', //Document path
'ua' => rawurlencode($_SERVER['HTTP_USER_AGENT']) //User Agent
);
ga_send_data($data);
}
然後,在你評論的位置,你只需將功能:
ga_send_event('Form Button', 'Submit', 'Feedback');
你的回答很有意義。由於我不熟悉PHP,因此我也有一位同事瀏覽它,他說它應該可以工作。出於某種原因,它不起作用。我打算把這個標記爲正確的答案,因爲它就是這樣。可悲的是,如果我不能很快弄清楚,我可能不得不使用不太準確的方法。感謝您的時間。 –
不知道您遇到的具體錯誤,我只需確保您已將自己的GA跟蹤ID替換爲「tid」值。您還需要將gearside.com的主機名更新爲您自己的主機名。在Google Analytics中,檢查實時事件報告,我甚至會在var_dump()''''var_dump()''''的靜態頁面(在表單外部)測試它,以確保它正常運行。 – GreatBlakes
一個可能的問題可能是'$ result = wp_remote_get($ getString)'這行'是WordPress特定的。使用從這個答案的代碼作爲替代似乎工作:http://stackoverflow.com/questions/1239068/ping-site-and-return-result-in-php –