In my WordPress Multisite, I use one theme for three sites, and a tracking code for analytics on my websites. Whether it is Google Analytics or Piwik (now Matomo) doesn't matter. Here is how you can conditionally add tracking codes to your WordPress Multisite: use a condition in functions.php to add the tracking code for Matomo or Google Analytics.
When several Multisite sites share one theme, use get_current_blog_id() in the theme's functions.php to pick the right analytics tracking code per site, and hook it into wp_footer with add_action().
Add conditional analytics tracking code in functions.php
Using the WordPress get_current_blog_id() function, it is easy to determine and retrieve the current blog ID. This is used for the condition to add the necessary tracking code to the footer. Further it is nothing more than an ugly if-then-else structure in functions.php :).
In your theme's functions.php, add the following PHP code to dynamically - or conditionally - add Google Analytics or Matomo tracking codes:
function saotn_piwik_multisite( ) {
$blog_id = get_current_blog_id();
$output = '';
if ( $blog_id == 1 ) {
// saotn.org
$output = '[tracking_code_1]';
}
else if ( $blog_id == 2 ) {
// itfaq.nl
$output = '[tracking_code_2]';
}
else if ( $blog_id == 3 ) {
// reilink.nl
$output = '[tracking_code_3]';
}
echo $output;
}
add_action( 'wp_footer', 'saotn_piwik_multisite', 100 );
Replace [tracking_code_#] with your JavaScript analytics tracking code.
Here, we use the wp_footer action with add_action() to place the tracking code as near to the closing </body> tag as possible. Use wp_head to load the analytics tracking code in your page's head section. References:
Google Analytics or Matomo in WordPress Multisite with a plugin
You can also add the Google Analytics or Matomo tracking code in your WordPress Multisite using a plugin. When I wrote this post, I mentioned Google Analytics by Yoast; that plugin lives on as MonsterInsights. For Matomo there is the official Matomo Analytics plugin.
More WordPress tweaks in functions.php and wp-config.php: add a delay to your WordPress login form, and increase WordPress' memory limit WP_MEMORY_LIMIT properly.