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.

JoshStauffer.com runs on the Genesis Framework

Genesis Framework

Genesis empowers you to quickly and easily build incredible websites with WordPress. Whether you're a novice or advanced developer, Genesis provides the secure and search-engine-optimized foundation that takes WordPress to places you never thought it could go. It's that simple - start using Genesis now!

Take advantage of the 6 default layout options, comprehensive SEO settings, rock-solid security, flexible theme options, cool custom widgets, custom design hooks, and a huge selection of child themes ("skins") that make your site look the way you want it to. With automatic theme updates and world-class support included, Genesis is the smart choice for your WordPress website or blog.

Become a StudioPress affiliate

Comments

  1. Thanks for the help getting Google Analytics setup for my domain!

  2. Lia says:

    I have a free wordpress site, what do I need to do to make google analytics, link within and advertise work with wordpress?
    Thanks
    L

  3. Rob Cubbon says:

    Thanks for this, Josh, handy if you have a child theme for Twenty Ten or something like that!

Speak Your Mind

*