How to Install Google Analytics on WordPress

Google Analytics is a free service that generates detailed statistics about the visitors to a website. Setting up and installing Analytics is one of the first things I do after launching a WordPress site. There are basically three ways to installing the script: copy and paste it in the theme’s header.php file, install a plugin like Google Analytics for WordPress or Google Analyticator, or insert the code into the theme’s function file (functions.php).

Since I prefer to use as few plugins as possible, I usually insert the code into the theme’s functions.php file using the wp_head action hook. Here’s the code that needs to be inserted into functions.php:

<?php
add_action('wp_head', 'insert_analytics_script');
function insert_analytics_script() {
?>
<script type="text/javascript">

	var _gaq = _gaq || [];
	_gaq.push(['_setAccount', 'UA-XXXXXXX-X']);
	_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
}
?>

Don’t forget to replace UA-XXXXXXX-X with your Analytics Web Property ID.