Google Analytics on WordPress Multisite

I recently had a need to add Google Analytics code to every site in a WordPress sub-folder multisite network.

Obviously, there are a lot of plugins for adding GA code to a WordPress site.  Most of these are intended for single sites – some will work on multisite, but they expect you to enter the tracking code on each site in the network.  In some cases this may be nice, as it allows you have different tracking codes for different sites, but it also allows an admin for each site to change the code.  That, coupled with the extra work of manually adding the code to each site led me down a different path.

*Note: There may be a multisite GA plugin out there, but it wasn’t plainly obvious to me after several minutes of searching.  I am rather picky about plugins, though.  Either way, the solution below works quite well for my case.

The other prominent method for adding GA to your site is putting the code in the functions.php file of your theme.  I would only recommend this if you are using a custom theme, otherwise it will be overwritten when you update the theme.  Additionally, this wouldn’t work well for us as we have several themes (some custom and some “out of the box”).  However, this method will work as a custom plugin – the benefit here being that I can “network activate” the plugin to add the code to every site in the multisite network.

If you need a crash course in creating WordPress plugins, WPBeginner has a list of resources, including the WordPress Codex.  If you’re looking for something in-depth, check out Brad William’s Professional WordPress Plugin Development book.

The code for the plugin is extremely simple:

<?php
add_action('wp_head', 'my_googleanalytics');
function my_googleanalytics() { ?>
<!--Put your Google Analytics code here-->
<?php } ?>

That’s it. Create your plugin with that code, install it into the /wp-content/plugins/ folder, and network activate it.

If you have a need to put the GA code in the page’s footer instead of the head, just change the “add_action” line to:

add_action('wp_footer', 'my_googleanalytics');

Tagged: Tags

6 Thoughts to “Google Analytics on WordPress Multisite

  1. Hi Phil!
    Thanks a lot for your article. This was my first WordPress plugin and I managed to have it installed in minutes after reading this.
    Regards,
    George.

      1. Thank you, Phil! You can specify in your article: this solution works also for WordPress/Buddypress Multisite Networks with subdomains if the function is putted in the bp-custom.php file (tested by me). I can see the Google Analytics code on subdomain blogs, no matter what theme is installed.

Leave a Reply

Your email address will not be published. Required fields are marked *