Skip to content

Instantly share code, notes, and snippets.

@zenman
Last active December 16, 2015 03:49
Show Gist options
  • Save zenman/5372296 to your computer and use it in GitHub Desktop.
Save zenman/5372296 to your computer and use it in GitHub Desktop.
Conditional Google Analytics code.
<?php
//hostname based google code, only run if on live site - By Tom Horak, modified by Tomas Mulder.
//placed right before closing head tag according to google best practice: https://support.google.com/analytics/answer/1008080?hl=en
$hostname = $_SERVER['HTTP_HOST']; //dev.zenman.com | localhost | Live server | etc..
switch ($hostname) {
case 'localhost': //do nothing
//echo '<!-- no google analytics code -->';
break;
case 'localhost:8888': //do nothing
//echo '<!-- no google analytics code -->';
break;
case 'dev1.zenman.com': //do nothing
//echo '<!-- no google analytics code -->';
break;
case 'test1.zenman.com': //do nothing
//echo '<!-- no google analytics code -->';
break;
case 'stage1.zenman.com': //mimic live environment...
?>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-00000000-0']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<?php
break;
default: //this is what you get on live server
?>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-00000000-0']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<?php
break;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment