2013-01-21 50 views
7

我想將我的Google Analytics代碼添加到Drupal站點而不使用模塊。我閱讀了與此相關的主題,但無法在我的網站上完成。我想把我的代碼放在<head></head>標籤中。這裏是我的代碼:如何將Google Analytics(分析)代碼添加到Drupal 7

<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> 
+2

任何特定的原因,你爲什麼要這樣做,而不使用模塊? –

+0

我也很好奇。我看不到有理由不使用該模塊,但是有理由使用某個模塊(例如,如果Google分析腳本中有任何更改,模塊可以更新嵌入的腳本) – Isaac

+1

如果您想要驗證爲在其他一些Google服務(例如Search Console)中擁有某個網站的所有者,您需要在「head」標籤內部使用Google Analytics代碼。 – maciek

回答

11

打開文件夾modules/system在你的Drupal安裝,然後複製html.tpl.php文件到您的主題目錄。將您喜歡的代碼添加到文件並保存。

不要忘記清除緩存。

+0

該文件將被複制到'MYTHEME /'目錄內?或者在「MYTHEME /模板」裏面?因爲我在那裏找到了我的'page.tpl.php'。 –

+0

任何地方都可以。這取決於你:) –

+0

我現在可以從源頭看到腳本。我怎麼知道我的JavaScript的作品? Thasnk! –

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')); 
    } 
?> 

一定要用你自己的UA ID和網站名稱。此外,請務必將THEME重命名爲主題,並在完成時清除緩存。

+0

+1。但爲什麼從'html.tpl.php'獲取代碼不太好呢? –

+0

谷歌分析給一個JavaScript代碼,也許這個代碼(JavaScript)將無法正常工作。 –

相關問題