How to add conditional analytics tracking code in WordPress Multisite

Photo of author
Written By Jan Reilink

Windows Server systems administrator & enthusiast.

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 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 Piwik/Matomo Analytics or Google Analytics.

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 IFTTT structure in functions.php :).

In your THEME functions.php, add the following PHP code to dynamically – or conditionally – add GA or Piwik/Matomo tracking codes:

function saotn_piwik_multisite( ) { $blog_id = get_current_blog_id(); if ( $blog_id == 1 ) { $output = '[tracking code_1]'; } else if ( $blog_id == 2 ) { $output = '[tracking code_2]'; } else if ( $blog_id == 3 ) { $output = '[tracking code_3]'; } echo $output; } add_action( 'wp_footer', 'saotn_piwik_multisite', 100 );
Code language: PHP (php)

and replace [tracking_code_#] with your JavaScript analytics tracking code.

Here, we use wp_footer() with add_action() to place the tracking code as near to the closing </body> tag as possible. Use wp_head() to load the tracking analytics code in your heading. References:

Google Analytics or Piwik/Matomo in WordPress Multisite with a Plugin

You can also add the Google / Piwik Analytics (now Matomo) tracking code in your WordPress Multisite using a plugin like Google Analytics by Yoast.


Did you like: How to add conditional analytics tracking code in WordPress Multisite

Then please, take a second to support Sysadmins of the North and donate!

Your generosity helps pay for the ongoing costs associated with running this website like coffee, hosting services, library mirrors, domain renewals, time for article research, and coffee, just to name a few.



Hi! Join the discussion, leave a reply!