在PHP中将Google Analytics事件添加到表单提交

3

我想在PHP表单成功提交后添加一个事件(已购买脚本)。我找到了在成功时触发的PHP函数,并标记了我认为要放置分析代码的位置...

function emailSuccessfullySent() {
global $translations, $lang, $options, $fdata, $is_ajax;

// redirect to custom "success" page if it's been set
if ( !empty($options['redirect_url'])) {
    if (!$is_ajax) {
        header('Location: '.$options['redirect_url']);
    } else {
        echo json_encode(array('redirect' => array($options['redirect_url'])));
    }
    exit;
}

// if no redirect has been set, echo out the success message
if ($is_ajax) {
    echo json_encode(array('success' => array($translations->form->success->title->$lang)));
    // analytics code here
} else {
    echo '<h2>'.$translations->form->success->title->$lang.'</h2>';
    // analytics code here
}

removeUploadsFromServer();
}

...但是我不确定如何触发JS事件:

ga('send', 'event', 'Form Button', 'submit', 'Feedback');
2个回答

5

您需要了解Google Analytics的服务器端测量协议

这里有一个我成功使用过的PHP实现,但它可能对于您的用例来说过于复杂(但至少是一个参考)。这是完整的代码,但我已经为这篇文章简化了它。

//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,我还让一位同事看了一眼,他说应该可以工作。但出于某种原因,它并没有起作用。我将把这个标记为正确答案,因为它确实是。不幸的是,如果我不能很快弄清楚,我可能不得不使用一种不太准确的方法。感谢您的时间。 - Ricardo Andres
如果您不知道遇到了什么具体错误,我建议您确保已经将“tid”值替换为您自己的GA跟踪ID。您还需要将主机名从gearside.com更新为您自己的主机名。在Google Analytics中,检查实时事件报告,并且我甚至建议您在静态页面(表单之外)上使用var_dump()进行测试,以确保一切都正常运行。 - GreatBlakes
3
可能存在的问题是该行代码 $result = wp_remote_get($getString); 是 WordPress 特定的。使用此答案中提供的代码作为替代方案似乎可行:https://dev59.com/1HM_5IYBdhLWcg3ww2Gb。 - Nick Mischler

0

另一个选项是在您的“成功”页面上设置目标。

成功提交表单后,用户将被重定向到成功页面并在Google Analytics中触发目标。


这是一个不错的备选方案,但目前表单提交后没有重定向到另一页。我现在正试图避免使用这个选项。 - Ricardo Andres

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接