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:

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');