How to Add Google Tag Manager After the Opening Tag in WordPress

Jaime Lernercoding 5 Comments

Oddly enough, WordPress still doesn’t have a native hook right after the opening <body> tag. Some themes add an action in that spot so you can hook into it, but most don’t.

Here is some simple code you can add to your WordPress functions file that will properly insert the iframe portion of the Google Tag Manager code after the opening <body> tag, and insert the rest after the opening of the <head> tag. Simply cut and paste this into the functions.php file of your theme (or child theme) replacing both instances of GTM-XXXX with your container ID.

Also note some of this is loaded via javascript AFTER your page loads, so you will not see it if you simply do a “view source”. Instead, you will need to “inspect” the code once your page is loaded and you will then see everything is inserted properly.

Please leave me a comment if this was helpful to you. :)

function gg_insert_gtm() { ?>
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-XXXX');</script>
<?php
}
add_action('wp_head','gg_insert_gtm');

IMPORTANT: The above code assumes you are inserting this code somewhere before the final php end tag (?>). IF you are inserting it AFTER the final php end tag (i.e. at the very end of your functions php file), then you will need to add in both a START php tag (<?php) at the very beginning before the word “function” AND an END php tag (?>) after the “add_action” line.

Also note the “noscript” portion isn’t here because it is for when you don’t have javascript and this obviously is inserted via javascript as pointed out. :) (Silly me on that one!)

Comments 5

  1. no script part is not correct. No script part works browsers that is not support javascript. But you’re try to append this code via jquery :)

    1. Post
      Author

      Oh mercy…I can’t believe I did that! You are absolutely correct. Thanks for pointing that out. :)

        1. Post
          Author

Leave a Reply

Your email address will not be published. Required fields are marked *