Search code examples
wordpressheadergoogle-tag-managertrackingcode-snippets

Google tag manager tracking code into the Wordpress header


I have Google Tag Manager code snippet and want to add it into the Wordpress header of the theme. Before the closing </head> tag I have <?php wp_head();>. Where to add the code snippet before or after the wp_head ? Which of these cases run pretty well, without any issues ?


Solution

  • Create a child theme before you add the GTM code on your own. Child theme prevents that theme updates overwrite your edited files and therefore disable the GTM.

    There are two codes that you need to insert - one needs to be in the head part, the other one needs to be in the body part.

    First part

    What we will do first is insert the code in the head part. Open your functions.php file and add this code below:

    /* This part adds the first GTM code in the header
    =====================================================*/
    function my_gtm_code1(){
    ?>
    
    // Insert the code provided by Google here
    
    <?php 
    }
    add_action( 'wp_head', 'my_gtm_code1', 10 );
    

    The "wp_head" part passes where you want this code to be added (obviously in the head), the "my_gtm_code1" is the name of the function, and number 10 states how high this code will be in the head (smaller the number, the higher the code will be in your head).

    Second part

    Next you will have to insert the code in the body part of your theme. As Wordpress core doesn't provide a hook for injecting functions in the body you will have to make a small workaround.

    First open your header.php file and add this bit of code right after the tag starts - <?php body_top(); ?>. Once this function is added then you can replicate the first part in your functions.php file, but for the 'noscript' code.

    /* This part adds the first GTM code in the header
    ========================================================*/
    function my_gtm_code2(){
    ?>
    
    // Insert the second code provided by Google here
    
    <?php 
    }
    add_action( 'body_top', 'my_gtm_code2' );
    

    And that's it - that's how you add GTM to your Wordpress site.

    Why this much work?

    Sure, you can do all this with a plugin, but with this you will learn a bit about how Wordpress works and what can you do with it. This may even help you with adding GA code or any other part that needs to be done in the head of Wordpress.