如何将Google Analytics代码添加到Drupal 7

kag*_*gat 7 php drupal google-analytics drupal-7 drupal-theming

我想在不使用该模块的情况下将我的Google Analytics代码添加到Drupal网站.我读了与此相关的线程,但我无法在我的网站上进行.我想把我的代码放在<head></head>标签里面.这是我的代码:

<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-XXXXXXX-X']);
  _gaq.push(['_setDomainName', 'example.com']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'stats.g.doubleclick.net/dc.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>
Run Code Online (Sandbox Code Playgroud)

Muh*_*eda 11

modules/system在Drupal安装中打开文件夹,然后将html.tpl.php文件复制到主题目录中.将您喜欢的代码添加到文件中并保存.

不要忘记清除缓存.


Eri*_*des 7

在Drupal站点上,您希望使用template.php文件中THEME_preprocess_html函数内的drupal_add_js函数插入其他javascript.这样做可以让您正确缓存您的网站.具体来说,这就是它的样子:

<?php
    function THEME_preprocess_html(&$variables) {

      $ga  = "var _gaq = _gaq || [];\n";
      $ga .= "_gaq.push(['_setAccount', 'UA-XXXXXXX-X']);\n";
      $ga .= "_gaq.push(['_setDomainName', 'example.com']);\n";
      $ga .= "_gaq.push(['_trackPageview']);\n";
      $ga .= "(function() {\n";
      $ga .= "  var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;\n";
      $ga .= "  ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';\n";
      $ga .= "  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);\n";
      $ga .= "})();\n";

      drupal_add_js($ga, array('type' => 'inline', 'scope' => 'header'));
    }
?>
Run Code Online (Sandbox Code Playgroud)

请务必使用您自己的UA ID和网站名称替换.此外,请务必将主题重命名为主题,并在完成后清除缓存.