There are many plugins available that handle this, but sometimes a simple solution works best. For most of the WordPress sites I design I implement this basic Google Analytics function into functions.php to keep things lightweight and not dependent on plugins. The only extra feature added to Google Analytics is 404 error tracking, which I always add.
The base_google_analytics() Function
I hope this helps you with your next project. As always, if you have any suggestions fire away!
About the Author
Kevin Leary is a web developer in Boston, MA specializing in enterprise website design and development, online marketing, and conversion optimization.
Thanks for this tip. Installing a plugin just to insert a few lines of standard code has got to be bad for server speed.
I made a couple of modifications which might be useful to others:
* don't insert tracking code for users that are logged in (eg admin – otherwise the site maintainers will distort the statistics)
* handle sites with subdomains, as per GA's suggested code
* put it in the header not footer – now "best practice" for the GA asynchronous script.
// Lightweight Google Analytics tracking code
function insert_google_analytics() {
if ( !is_user_logged_in() ) {
?>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXXXX-1']);
_gaq.push(['_setDomainName', 'YOURDOMAIN.com']);
<?php if( is_404() ){ ?>
_gaq.push(['_trackPageview', '/404/?page=' + document.location.pathname + document.location.search + '&from=' + document.referrer]);
<?php } else { ?>
_gaq.push(['_trackPageview']);
<?php } ?>
(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
}
}
add_action('wp_head', 'insert_google_analytics');
Incidentally there's a plugin, Reporteur (http://wordpress.org/extend/plugins/reporteur) which is supposed to just query your Analytics data and display some simple reports inside WP's admin area, which should work together with this method. I say "supposed to" because currently it's not working for me with 3.4.2, but perhaps it'll be updated soon.