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: @HertogJanR */
  $blog_id = get_current_blog_id();
  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 );

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 this post helped you solve a problem? Or dit you find it interesting? Support Sysadmins of the North with a direct donation via Paypal of by bank wire transfer IBAN: NL31 ABNA 0432217258 (Jan Reilink). Just $ 5,- or € 5,- is more than enough, thanks!

Read this too:   Always_populate_raw_post_data setting in PHP 5.6 & Magento 2.0

Support SAOTN.ORG


228 views

Leave a Reply

Your email address will not be published. Required fields are marked *