-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwordpress-ga-user-id.php
84 lines (70 loc) · 2.58 KB
/
wordpress-ga-user-id.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<?php
/*
Plugin Name: Google Analytics User ID Helper
Plugin URI: http://web.peterhartree.co.uk/
Description: Enables user ID tracking using Google Analytics. User ID value must be alphanumeric.
Version: 0.1
Author: Peter Hartree
Author URI: http://web.peterhartree.co.uk/
Dependencies: Constant GOOGLE_ANALYTICS_ID must be set to a valid Universal Analytics tracking ID in your theme's functions.php.
*/
$ga_user_id_safe = false;
function google_analytics_user_id() {
if(GOOGLE_ANALYTICS_ID):
global $ga_user_id_safe;
$ga_user_id_safe = get_google_analytics_user_id();
if($ga_user_id_safe):
// Add Google Analytics tracking script with User ID set.
add_action('wp_footer', 'script_google_analytics_user_id', 20);
// Remove the Google Analytics code set by Roots.io theme
if(!current_user_can('manage_options')):
remove_action('wp_footer', 'roots_google_analytics', 20);
endif;
else:
// User ID wasn't passed.
// => DO NOTHING (assume the regular Google Analytics tracking code
// will be injected elsewhere)
endif;
endif;
}
add_action('init', 'google_analytics_user_id');
function get_google_analytics_user_id() {
$ga_user_id_safe = false;
// Has the user ID already been set in a session cookie?
if(isset($_COOKIE['google_analytics_user_id'])):
$ga_user_id = $_COOKIE['google_analytics_user_id'];
$ga_user_id_safe = sanitize_google_analytics_user_id($ga_user_id);
endif;
// Is the user ID being passed via a querystring?
if(isset($_GET['ga_user_id'])):
$ga_user_id = $_GET['ga_user_id'];
$ga_user_id_safe = sanitize_google_analytics_user_id($ga_user_id);
setcookie('google_analytics_user_id', $ga_user_id, time() + (86400 * 7));
endif;
return $ga_user_id_safe;
}
function sanitize_google_analytics_user_id($ga_user_id) {
if(ctype_alnum($ga_user_id)):
$ga_user_id_safe = $ga_user_id;
endif;
return $ga_user_id_safe;
}
function script_google_analytics_user_id() {
global $ga_user_id_safe;
echo "
<script>
(function(b,o,i,l,e,r){b.GoogleAnalyticsObject=l;b[l]||(b[l]=
function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date;
e=o.createElement(i);r=o.getElementsByTagName(i)[0];
e.src='//www.google-analytics.com/analytics.js';
r.parentNode.insertBefore(e,r)}(window,document,'script','ga'));
ga('create','". GOOGLE_ANALYTICS_ID . "', { 'userId': '" . $ga_user_id_safe . "'});
ga('set', {
'dimension1': '" . $ga_user_id_safe . "',
'metric1': '" . $ga_user_id_safe . "'
});
ga('send','pageview');
</script>
";
}
?>