How to insert Google Tag Manager code into pages with variable account value I need to insert the Google Tag Manager snippet code into each page just after the opening &lt;body&gt; tag. This is fine, except I would also like the user to specify the account number in an admin form, so what is put in this form will be output in the snippet.

In the snippet, the account number is required twice:

&lt;noscript&gt;&lt;iframe src="//www.googletagmanager.com/ns.html?id=&lt;ACCOUNT NO HERE&gt;"
...
(window,document,'script','dataLayer','&lt;ACCOUNT NO HERE&gt;');&lt;/script&gt;


Setting up the admin form and storing and retrieving it by variable_set() and variable_get() is no problem, but what's the best way to insert it into the template?

My thought is to use hook_preprocess_page(), but I'm not sure if this is the right hook to use, and if it is - what part of the array I would need to change to get this to appear? Or would a better way would be to make a variable available to the tpl.php file and insert it there? In which case, how would this be achieved? Thanks!
you should use these two modules:

https://www.drupal.org/project/google_tag

https://www.drupal.org/project/datalayer

First one installs GTM on your page, second one enables passing many variables and taxonomies to be passed to dataLayer. It also has an alter function, if you'd like to add some extra data (since the module is written in a general way and i.e. extracting taxonomies from json arrays on the GTM side can be complicated).

User Id is part of default data added to dataLayer by data layermodule on each page, so you'll have it there.

Regarding your noscript part, you'd have to alter the module i think.