Skip to content

Instantly share code, notes, and snippets.

@macedd
Last active September 14, 2017 17:48
Show Gist options
  • Save macedd/a769f820cfec4e9389d77fc5fb261f07 to your computer and use it in GitHub Desktop.
Save macedd/a769f820cfec4e9389d77fc5fb261f07 to your computer and use it in GitHub Desktop.
PHP Google Analytics WordPress Example
<?php
require_once dirname( __FILE__ ) . '/lib/php-ga/src/autoload.php';
use UnitedPrototype\GoogleAnalytics;
if (!function_exists('ga_tracker')) {
function ga_tracker() {
// Initilize GA Tracker
$tracker = new GoogleAnalytics\Tracker('UA-12345678-9', 'website.com');
return $tracker;
}
function ga_visitor() {
// Assemble Visitor information
// (could also get unserialized from database)
$visitor = new GoogleAnalytics\Visitor();
$visitor->setIpAddress($_SERVER['REMOTE_ADDR']);
$visitor->setUserAgent($_SERVER['HTTP_USER_AGENT']);
return $visitor;
}
function ga_session() {
// Assemble Session information
// (could also get unserialized from PHP session)
$session = new GoogleAnalytics\Session();
return $session;
}
function ga_page($uri=null, $title=null) {
if (!$uri)
$uri = $_SERVER['REQUEST_URI'];
if (!$title)
$title = get_the_title();
// Assemble Page information
$page = new GoogleAnalytics\Page($uri);
$page->setTitle($title);
return $page;
}
function ga_event($category = null, $action = null, $label = null, $value = null, $noninteraction = null) {
$event = new GoogleAnalytics\Event($category, $action, $label, $value, $noninteraction);
return $event;
}
function track_event($category, $action, $label = null, $value = null) {
$tracker = ga_tracker();
$event = ga_event($category, $action, $label, $value);
$session = ga_session();
$visitor = ga_visitor();
$page = ga_page();
$tracker->trackEvent($event, $session, $visitor, $page);
}
}
@macedd
Copy link
Author

macedd commented Sep 14, 2017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment