How to add conditional analytics tracking code in WordPress Multisite

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( ) {
  /* follow me on Twitter: @Jan_Reilink */
  $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.

Jan Reilink

Hi, my name is Jan. I am not a hacker, coder, developer or guru. I am merely an application manager / systems administrator, doing my daily thing at Embrace - The Human Cloud. In the past I worked for clidn and Vevida. With over 20 years of experience, my specialties include Windows Server, IIS, Linux (CentOS, Debian), security, PHP, websites & optimization. I blog at