How to add Google Tag Manager in 1 Minute
Go to Google Tag Manager Setup. You should receive to Javascript code snippet you need to add to your website, one in the header and one just after the body starts.
There are two simple hooks you can use:
add_action('wp_head', 'add_my_code_to_header');
function add_my_code_to_header(){
?>
<?php
}
function add_my_code_right_after_body_starts() {
?>
<?php
}
add_action( 'wp_body_open', 'add_my_code_right_after_body_starts' );
In short, open your theme's functions.php and enter the following code. You can either switch the GTM ID or copy the whole thing:
add_action('wp_head', 'add_google_analytics_code_to_header');
function add_google_analytics_code_to_header(){
?>
<!-- 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-56ZV94K');</script>
<!-- End Google Tag Manager -->
<?php
}
function add_right_after_body_starts() {
?>
<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-56ZV94K"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->
<?php
}
add_action( 'wp_body_open', 'add_right_after_body_starts' );
Refresh your page and try to verify the installation in Google Tag Manager!