Google Analytics Tracking in WordPress Without a  Plugin

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


/** * Google analytics attached to footer */ function base_google_analytics() { ?> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-XXXXXX-1']); <?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' : 'https://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <?php } add_action('wp_footer', 'base_google_analytics');

I hope this helps you with your next project. As always, if you have any suggestions fire away!