You are here

function datalayer_google_tag_snippets_alter in dataLayer 8

Implements hook_google_tag_snippets_alter().

If the google_tag module is installed, avoid conflicts with the datalayer variables.

File

./datalayer.module, line 562
Client-side data space.

Code

function datalayer_google_tag_snippets_alter(&$snippets) {
  $config = \Drupal::config('google_tag.settings');
  $data_layer = $config
    ->get('data_layer');
  $data_layer = trim(json_encode($data_layer), '"');

  // Combine the dataLayer module variable with the google_tag dataLayer array.
  $init_value = $data_layer === 'dataLayer' ? 'window.dataLayer' : "window.dataLayer || window.{$data_layer}";
  $snippets['data_layer'] = preg_replace("/.*({$data_layer}) =.*?\\[(.*)\\](;.*\$)/", 'window.$1 = ' . $init_value . ' || []; window.$1.push($2)$3', $snippets['data_layer']);
}