This tutorial provides the steps on How to add Google Tag Manager code in Genesis based child themes.
STEP 1
Go to https://tagmanager.google.com/ and log in with your Gmail account.
You will be redirected to the Tag Manager account.
STEP 2
Click on Create Account from the right top and fill the details
and Click “Create”.
Read and Accept the Terms of Service agreement and Click Yes.
STEP 3
A new Page with Pop up like this will appear. The first code is for javascript enabled browser and the other one will be used when Javascript is not available in the Browser.
Remember the GTM-XXXX id.
STEP 4
Open functions.php of your child theme and add the following.
//* Add Google Tag Manager code in <head> add_action( 'wp_head', 'dy_google_tag_manager_js' ); function dy_google_tag_manager_js() { ?> <!-- 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-XXXX');</script> <!-- End Google Tag Manager --> <?php } //* Add Google Tag Manager code immediately after opening <body> tag add_action( 'genesis_before', 'dy_google_tag_manager_no_js' ); function dy_google_tag_manager_no_js() { ?> <!-- Google Tag Manager (noscript) --> <noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-XXXX" height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript> <!-- End Google Tag Manager (noscript) --> <?php }
Replace the sample code mentioned in the above function with the code provided by Google Tag Manager in STEP 3 or Replace GTM-XXXX with your container ID.
Output:
Reference: https://developers.google.com/tag-manager/quickstart
Marcus says
Does it matter where you place the code in the functions.php file? Before any of the other code, or at the bottom, after all the code thats already in there?
Aryan Raj says
Hi, Pasting the code at the bottom ensure that we have not mixed the code. This also helps us to easy management, easier to find the custom code. Mixing codes with original theme code will make things complicated when you ever want to remove them.