How to change the Web Property ID of Google Analytics per hostname / domain / language in Drupal 8
This can be done for almost anything not just for Google Analytics, so what we are going to do here is override exportable configs in settings.php so we can add conditional logics to it.
So for example if you want to override the Google Analytics Web Property ID in Drupal 8, you can use the following.
$config['google_analytics.settings']['account'] = 'UA-XXXXXX-X';
How you do conditional, let's say you want your Google Analytics Web Property ID is available only in your production environment, here is how you do that for Acquia cloud or Pantheon.
For Acquia:
/**
* Set google analyics tracking code for production.
*/
if (isset($_ENV['AH_SITE_ENVIRONMENT'])) {
if ($_ENV['AH_SITE_ENVIRONMENT'] == 'prod') {
$config['google_analytics.settings']['account'] = 'UA-XXXXXXXX-Z';
}
}
For Pantheon:
if (PANTHEON_ENVIRONMENT == 'dev') {
In addition to those you can use different conditional logics too.
// Override Google Analytics Web Property ID per hostname.
// Hostnames need to be lower-case!
switch ($_SERVER['HTTP_HOST']) {
case 'www.example.com':
case 'www.example.net':
case 'forum.example.net':
© Heshan Wanigasooriya.RSS🍪 This site does not track you.