skip to Main Content

I’m trying to add the Google Tag Manager scripts on my WordPress website, custom theme with locomotivescroll.js and swup.js. Here is the code I use for the integration in functions.php:

/* Google Tag Manager
/* ------------------------------------ */
add_action( 'wp_head', 'add_gtm_head', 10 );
function add_gtm_head() { ?>
    <!-- Google Tag Manager -->
    <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-XXXXXXX');</script>
    <!-- End Google Tag Manager -->
<?php
}

add_action( 'body_top', 'add_gtm_body' );
function add_gtm_body() { ?>

<!-- Google Tag Manager (noscript) -->
    <noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-XXXXXXX"
    height="500" width="100%"></iframe></noscript>
    <!-- End Google Tag Manager (noscript) -->

<?php
}

If I test the preview on GTM I receive the "can’t connect to the website", but if I go in the source code of the homepage I find the script in the and the other in the top-body.
In header.php I put:
<?php wp_head(); /* insert scripts and tags in header */ ?> in the head and
<?php do_action('body_top'); ?> at the beginning of the body

Anyone who can help me? Are there some issues with the Js libraries mentioned before?

2

Answers


    1. Do you actually add GTM with GTM-XXXXXXX? Those Xs are supposed to be replaced with your GTM ID.
    2. We usually don’t use php to inject a GTM snippet. We typically either inject them in html templates, maybe creating a child theme. Or just use an extension to load it.
    3. Finally, make sure the GTM snippet appears in your DOM (Elements section of Chrome debugger) as it appears in GTM UI. It gives you the actual content of the tag as it should appear in your DOM.
    Login or Signup to reply.
  1. @carlvash You don’t need to manually insert any GTM code if you use the Site Kit plugin by Google. The plugin does it for you, and it’s free! Once inserted you’ll notice the correct snippets appearing on your site, while including your own GTM container ID (in place of the GTM-XXXXXXX you referenced)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search