Google Tag Manager is the best way to manage website tags without editing code to the website directly. You can use it to setup Google Analytics and Google Ads. With a single platform to handle all the configuration, without touching the website code, you will soon realise how powerful this is, and how this will change your way to do online marketing.

This article covers how you can add Google Tag Manger to your website.

Google Tag Manager Setup

Sign in to the GTM console, add an account. An Google Tag Manager ID will be assigned to you, and terse are 2 code blocks available like this:

Here you will have the code you need for installation.

Option 1: Using Plugin

The easiest way is to find a plugin to take care of the installation work for you. We recommend Google Tag Manager for WordPress.

The rest of the step is easy. All you need to do is enter the Google Tag Manager ID in the textbook and save it.

Option 2: Write Your Own Code

This is actually what we suggest to do instead of using plugin. Because such task is really simple. It’s not worth to add an extra plugin dependency to your WordPress.

There are 2 action hooks you need:

wp_head()

We are going to add the first code block into the <head></head> tag using this hook.

wp_body_open()

This hook is immediately fired after opening the body tag. We are going to use this to add the second code block.

Below is sample that you can put into functions.php. Make sure you are replacing your own code block instead of just copy n paste the sample because the GTM ID of each code block is different.

add_action( 'wp_head', function() {
    if ( ! is_admin() && !current_user_can( 'administrator' ) ) {
        ?>
<!-- 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
      }
}, 0 );

add_action( 'wp_body_open', function() {
    if ( ! is_admin() && !current_user_can( 'administrator' ) ) {
        ?>
<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-XXXXXXX"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->
        <?php
    }
}, 1 );

Above two action hooks are very standard WordPress hooks, so it should work in most of the themes.