Skip to content

Instantly share code, notes, and snippets.

@adamwalter
Last active October 19, 2018 04:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamwalter/5dfbf7e75e9291e37e1b to your computer and use it in GitHub Desktop.
Save adamwalter/5dfbf7e75e9291e37e1b to your computer and use it in GitHub Desktop.
Tracking WordPress Data in Google Analytics
<?php
/**
* Enqueue ga.js and pass PHP variables into it
*/
function ga_script_enqueuer() {
wp_enqueue_script('ga', get_template_directory_uri() . 'ga.js');
if (is_user_logged_in()) {
$user = wp_get_current_user();
$ga_user_data = array(
'username' => $user->user_login
);
}
if (isset($ga_user_data)) {
wp_localize_script('ga', 'User', $ga_user_data);
}
}
add_action('wp_enqueue_scripts', 'ga_script_enqueuer');
/**
* Redirect user to custom URL after comment submission
*/
function redirect_after_comment($location) {
$location = $location . '?submitted=1';
return $location;
}
add_filter('comment_post_redirect', 'redirect_after_comment');
?>
/**
* Get URL parameters
* http://www.onlineaspect.com/2009/06/10/reading-get-variables-with-javascript/
*
* @param {string} q Name of the parameter to get
* @param {string} s Static URL as string to get the parameters.
* Leave empty to get current window location.
* @return {string} Value of variable
*/
function $_GET(q, s) {
s = s ? s : window.location.search;
var re = new RegExp('&'+q+'(?:=([^&]*))?(?=&|$)','i');
return (s=s.replace(/^\?/,'&').match(re)) ? (typeof s[1] == 'undefined' ? '' : decodeURIComponent(s[1])) : undefined;
}
/**
* Google Analytics Base Code
*/
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-XXXXXXXX-Y', 'auto');
/**
* Custom Dimension
*/
if (typeof User === 'object') {
var username = User.username;
if (username) {
ga('set', 'dimension1', username);
}
}
ga('send', 'pageview');
/**
* Custom Event
*/
document.addEventListener('DOMContentLoaded', function(event) {
// #important_btn click
var importantBtn = document.getElementById('important_btn');
importantBtn.addEventListener('click', function() {
ga('send', 'event', 'button', 'click', 'Important Button');
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment