How to add Google Analytics code on Drupal 7

I want to add my Google Analytics code to my Drupal site without using a module. I have read the topics related to this, but I cannot do this on my website. I want to put my code in the <head></head> . Here is my code:

 <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> 
+7
source share
2 answers

Open the modules/system folder in your Drupal installation, then copy the html.tpl.php file to your theme directory. Add the code you like to the file and save.

Remember to clear the cache.

+11
source

On the Drupal site, you want to insert additional javascript using the drupal_add_js function inside the THEME_preprocess_html function in the template.php file. This allows you to cache your site correctly. In particular, it will look like this:

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

Be sure to replace the UA identifier and website name with yours. Also, be sure to rename THEME to your theme and clear the cache when done.

+7
source

All Articles