Search code examples
javascriptgoogle-analyticsgoogle-tag-managerfacebook-pixel

How can I add tags at different HTML positions in Google Tag Manager?


Currently, the GTM script is added within the <head> section on all the pages of our site. So, naturally, when I add tags to the GTM, they are all added to the <head> section.

However, it seems like for certain pixel conversion script snippets, they need to be added outside of the section or within the section.

For instance, I need to add <script>fbq('track', 'Purchase');</script> right after the tag.

And for Google's conversion pixel, I need their snippet within the <body> section.

How can I control the placement of the tags in GTM?


Solution

  • It is not possible to control the placement of the tags in Google Tag Manager. It is possible to control the execution of the tag.

    What I would suggest for Facebook Conversion pixels is use a custom HTML tag. Insert the code to your pixel there and wrap the pixel code in HTML tags.

    For example:

    <html>
    <!-- Facebook Pixel Code -->
    <script>
    !function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod?
    n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n;
    n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0;
    t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window,
    document,'script','https://connect.facebook.net/en_US/fbevents.js');
    fbq('init', 'XxXXxXXXXXXXX'); // Insert your pixel ID here.
    fbq('track', 'PageView');
    </script>
    <noscript><img height="1" width="1" style="display:none"
    src="https://www.facebook.com/tr?id=XxXXxXXXXXXXX&ev=PageView&noscript=1"
    /></noscript>
    <!-- DO NOT MODIFY -->
    <!-- End Facebook Pixel Code -->    
    </html>
    

    More instructions can be found here: [https://www.facebook.com/business/help/1021909254506499][1]

    Then you can set the trigger to fire on pageview, DOM ready or window loaded. When the tag loads via GTM it doesn't mean it executes. By setting the