Like the blog? Get the book »

5+ Ways to Add Google Analytics to WordPress

5+ Ways to Add Google Analytics to WordPress

Delivered on Google’s “world-class platform,” Google Analytics is a powerful way to monitor your site’s statistics. As flexible content-publishing software, WordPress provides a variety of ways to add Google Analytics (GA) to your web pages. These techniques range from including the GA tracking code directly to using plugins that are easy to customize from within the WP Admin area. In this DigWP post, we cover it all with 5+ ways to add Google Analytics to your WordPress-powered site.

Add Google Analytics to WordPress

Probably the most convenient way to add Google Analytics to your site is via plugin. There are many available, but they all essentially do the same thing: add the required GA code to your web pages. So no need to list all 5,000 of them. Instead, let’s explore some plugins that range in functionality — from extreme to minimal — and then look at how to add the tracking code without a plugin.

Google Analytics for WordPress

Google Analytics for WordPress Joost’s Google Analytics for WordPress is probably the most comprehensive way to integrate GA with your site. It’s a fully customizable plugin providing control over the tracking code: where it’s located, and what it tracks, and how it’s used. Here are some of the best features for the Google Analytics for WordPress plugin:

Features

  • Simple installation
  • Asynchronous tracking
  • Supports custom location of tracking code
  • Automatic site speed tracking
  • Tracks outbound/external links, downloads, logins, registrations
  • Supports custom variables (e.g., author, category, et al)
  • Supports local hosting of the ga.js file

Plus gobs of other cool features that really make this a one-stop shop for complete/custom integrations of Google Analytics with WordPress. Installing this plugin is easy, but may take some time to configure everything to best suit your needs. If you need that level of control, this plugin is your best bet.

Google Analyticator

Google Analyticator Ronald Heft’s Google Analyticator plugin is another great way to integrate GA with your WordPress-powered site. In addition to plenty of configurable options, Google Analyticator features two ways to view recent statistics from the comfort of your own site. Shown at left is a screenshot of the front-end widget that displays the hit count of each page. And then in the Admin area, Google Analyticator includes a Dashboard widget that displays all your latest statistics. Here is a screenshot:

Google Analyticator Dashboard StatisticsGoogle Analyticator Dashboard widget displaying latest stats

Features

  • Easy installation (don’t even need your UID)
  • Asynchronous tracking
  • Dashboard widget with latest statistics
  • Front-end widget displaying latest stats
  • Tracks outbound/external links, downloads, and site speed
  • Supports any advanced tracking code Google provides
  • Supports localization

There are more features, but these are the main ones that make the plugin great. If you’re looking for a solid GA plugin that’s easy to customize with a good set of options, Google Analyticator is a great choice. Plus you get the awesome front-end and Dashboard widgets to display your statistical data on-site.

Google Analytics Plugin

Google Analytics Plugin The Google Analytics Plugin enables you to add the asynchronous tracking code from the comfort of the WP Admin. I designed this plugin to be as minimal and basic as possible — it’s just one small file that makes it easy to enable/disable GA tracking on your WordPress-powered site. After activating the plugin, visit the Settings page to add your GA property ID and done. No fuss no muss.

Here is a screenshot of the plugin’s Settings page:

Google Analytics PluginBasic settings page for the Google Analytics Plugin

Features

  • Blazing fast performance
  • Does one thing and does it well
  • Drop-dead simple and easy to use
  • Uses latest version of GA Tracking Code
  • Includes GA Tracking Code in header or footer
  • Inserts your tracking code on all theme pages
  • Includes option to add your own custom markup

If you need a clean, simple way of adding the GA tracking code from within the WP Admin area, the Google Analytics Plugin is the way to go. The only simpler way of doing it is to add the tracking code directly, which we’ll explain after checking out one more notable plugin..

Full disclosure: I am the author the of this plugin :)

Google Analytics Dashboard

Google Analytics Dashboard Before we look at adding Google Analytics without a plugin, I want to mention the extremely useful Google Analytics Dashboard. This popular plugin displays your site’s statistical data in the WP Dashboard. This is extremely handy for keeping track of things without having to log in to your Google account. Overall it’s a great plugin, but there is something worth mentioning..

As explained by staze, the GAD plugin collects a ton of data in the database, which can lead to excessive table sizes. So if you happen to be using this plugin, you may want to keep an eye on things with one of the following SQL queries:

SELECT option_name FROM wp_options WHERE option_name LIKE '_transient_timeout%' AND option_value < now();
SELECT option_name FROM wp_options WHERE option_name LIKE '_transient_gad%' AND option_value < now();
SELECT option_name FROM wp_options WHERE option_name LIKE '_transient_gad%';

If it looks like things are out of control size-wise, staze explains how to clean it up automatically using the following code in your theme’s functions.php file:

add_action( 'wp_scheduled_delete', 'delete_expired_db_transients' );
function delete_expired_db_transients() {
    global $wpdb, $_wp_using_ext_object_cache;
    if( $_wp_using_ext_object_cache )
        return;
    $time = isset ( $_SERVER['REQUEST_TIME'] ) ? (int)$_SERVER['REQUEST_TIME'] : time() ;
    $expired = $wpdb->get_col( "SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE '_transient_timeout%' AND option_value < {$time};" );
    foreach( $expired as $transient ) {
        $key = str_replace('_transient_timeout_', '', $transient);
        delete_transient($key);
    }
}

Once you’ve got a lid on the size of your database, the Google Analytics Dashboard is a great way to monitor your recent stats without leaving your site.

Add GA without a plugin

As explained in the Quickstart guide, setting up Google Analytics on your site involves the following steps:

  1. Add your GA property ID to the tracking-code snippet (below)
  2. Include the tracking snippet in your web page(s)

That’s really all there is to it. The tracking snippet is a bit of JavaScript that activates Google Analytics by inserting the ga.js code into the page. Note that JavaScript is widely used, but not every browser supports it (either natively or by user-choice). Something to keep in mind, that non-JS visits aren’t recorded in Analytics. </digression>

GA Tracking Code

To enable asynchronous GA tracking, replace the “UA-XXXXX-X” with your property ID and paste the entire code snippet into your web page(s) in either of the following locations:

  • Just before the closing </head> tag (recommended by Google)
  • Just before the closing </body> tag (may improve performance)

For either location, the code is the same:

<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-XXXXX-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>

Note that this is the basic asynchronous tracking code, and may be customized for advanced tracking using the methods available in the API. Here is more information about setting up the tracking code.

Add GA via functions.php

With WordPress, there are at least three good ways to include content (scripts, markup, text, et al) in your web pages:

  • Paste directly in your theme template file (e.g., footer.php)
  • Include via your theme’s functions.php file
  • Add the code via plugin, as described previously

To add the tracking code directly, just open your theme’s footer.php file and paste the snippet just before the closing </body> tag. Upload the file to the server and done. The GA tracking code will now be included on all of your public WP pages (posts, archives, pages, et al).

To add the code via the functions.php file, just add the following code to your active theme’s functions.php file:

// Include the Google Analytics Tracking Code (ga.js)
// @ https://developers.google.com/analytics/devguides/collection/gajs/
function google_analytics_tracking_code(){

	$propertyID = 'UA-XXXXX-X'; // GA Property ID

	if ($options['ga_enable']) { ?>

		<script type="text/javascript">
		  var _gaq = _gaq || [];
		  _gaq.push(['_setAccount', '<?php echo $propertyID; ?>']);
		  _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 }
}

// include GA tracking code before the closing head tag
add_action('wp_head', 'google_analytics_tracking_code');

// OR include GA tracking code before the closing body tag
// add_action('wp_footer', 'google_analytics_tracking_code');

As-is, this code will add the tracking code just before the closing </head> tag, which is the way that Google recommends doing it. There are reasons, however, for including the code near the end of the page, just before the closing </body> tag. For example, when tracking code is included in the <head> section, a visit is recorded even if the entire page isn’t loaded. Whether this is desirable or not is up to you, but there are also performance benefits to consider.

So, for the WordPress function above, if you would rather include the tracking snippet before the closing </body> tag, uncomment the last line and comment-out the one before it (i.e., add_action('wp_head',..) and you’re all set.

Even more..

Just wanted to emphasize that there are many different GA-related plugins in the WP Plugin Directory and elsewhere online — so if something here doesn’t work for you, search around or even roll your own. And if you happen to know of any good GA-related plugins that should be included, feel free to shout ’em out in the comments. As always, thanks for reading :)

20 responses

  1. Yes, adding Google analytics code in theme option panel is a easy task, 2nd option is adding code in header.php code. other options will be difficult to follow. Anyways thanks for the article Jeff.

  2. Thanks for this list but which method do you use on this blog?

    Personally, i use paste the code into the theme and that’s it but thanks for reminding me of the Dashboard plugin.

    I’ve already got WordPress.com stats which are very limited but i should dig deeper into GA.

    • We just include the code manually here at DigWP.com :)

      We tried the GA Dashboard for awhile but kept having to go in and manually truncate the db tables, so finally removed it.

    • clear enough. I will try it. Let’s see if it works :)

  3. Thanks for the great summary! I’d always wondered why bother with a plugin when it’s easy enough to add the code yourself, but I see there some expanded functions and benefits.

    I’m not using a plugin and have been running GA before my closing tag. I’d been having trouble getting my Goals in GA to track properly and read somewhere that moving the tracking code up to the header (where Google recommends) would correct that. Just switched the code location, so we shall see!

  4. Jeff, my plugin Add to all allows users to integrate GA, besides supporting several other features.

    It’s a simple configuration that adds the necessary code. It’s ideal for users who don’t want to view all the statistics etc from within their Dashboard, but prefer a quick simple method to add the code without editing any theme files.

  5. Any advise for UK based websites? The new cookie law means we need viewer consent before dumping cookies on ’em!

    • Yeah, I’ve been meaning to ask what the heck is going on with the cookie law in the UK.. how on earth was such an idea even taken seriously, let alone passed into law. Not sure how I would deal with that — it makes it difficult to collect data via any sort of cookie-based tracking..

      • If I’m not mistaken you need to push up a notification to UK based viewers that you have a “cookie policy” which they can choose to read or ignore.

        My suggestion is to implement a popup plugin to display this notification. However, you might need to modify the same to detect IP of the user and display if it is a UK IP.

  6. Thanks, those are good tips

  7. Good round-up article Jeff. Been a fan of your great articles. Instead of creating a custom filter in GA, is there a code snippet to not track wordpress admin (and his IP dynamic/static) ?

    • Yes, the functions.php snippet inserts the tracking code into theme files only, via wp_head or wp_footer:

      // include GA tracking code before the closing head tag
      add_action('wp_head', 'google_analytics_tracking_code');

      // OR include GA tracking code before the closing body tag
      // add_action('wp_footer', 'google_analytics_tracking_code');

      So no tracking of any Admin pages :)

  8. Very Nice Post! Thanks

  9. Hey Jeff,

    Good article, thanks :) I just wanted to let you know that Google Analyticator is no longer will be supported as of 6th June 2012.

    Any tips what plugins would display the GA stats in the admin?? I was told that Jetpack is good. Although, I can’t test it yet as I’m a staging site and it looks like it comes with whole bunch of other things… Would be great to have a dedicated plugin to see GA stats only.

    Thanks in advance.
    Dasha

    • Hi Dasha,

      Thanks for the info! I’ll have to find a good mid-range plugin for the article.. the good news is that there are many to choose from, so it’s all good. The best one I’ve seen for actually displaying stats is the Google Analytics Dashboard, but the database-size issue is disconcerting. Have not tried Jetpack, but it does look cool. Let us know if you try it or find a good plugin for GA-stats display.

    • Right, a fellow developer at the local Brighton WP group has recommended to use Analytics360 (from MailChimp) purely for stats display in the admin interface, not tracking. It shows stats under the main “Dashboard” menu, the main important info – nice and clean.

      You would need to authenticate your site via the plugin, before you can do that you would need to register your site with Google.

      I hope that helps someone. I’m loving this setup! :)

      Dasha

  10. P.S. Thanks Stefan Pause for recommending Analytics360 (from MailChimp) for G.A. stats display in WP admin. :)

  11. I am trying to figure out how to put a third party companies tracking code on only one page of the site, the form submission. Is there anyway to do that?

  12. I use ‘Google Analyticator’ to display stats on my wordpress website. It is very handy to see the recent visitor stats without having to log in to Google Analytics every day.

Comments are closed for this post. Contact us with any critical information.
© 2009–2024 Digging Into WordPress Powered by WordPress Monzilla Media shapeSpace