Sysadmins of the North
Don't forget to share this post!

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 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 tracking codes:

function saotn_piwik_multisite( ) {
  /* follow me on Twitter: @HertogJanR */
  $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 );

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:

This may interest you:   Magento maintenance script for IIS

Google Analytics or Piwik in WordPress Multisite with a Plugin

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

About the Author Jan Reilink

My name is Jan. I am not a hacker, coder, developer, programmer or guru. I am merely a system administrator, doing my daily thing at Vevida in the Netherlands. With over 15 years of experience, my specialties include Windows Server, IIS, Linux (CentOS, Debian), security, PHP, WordPress, websites & optimization. Want to support me and donate? Use this link:

follow me on:

Leave a Comment:

Skip to content