Hello there,
you can procede in 2 ways: via plugin or via custom code.
PLUGIN SOLUTION)
you can install one of the following:
– Insert Headers and Footers by WPBeginner
– Google Tag Manager for WordPress
I tested successfully both of them.
CODE SOLUTION)
Add this code in your child theme functions.php file. Be sure to replace the whole GTM code since it is just an example.
/*
* Insert Google Analytics Code in <head> tag
*/
function add_my_gtm_to_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-XXXXXX');</script>
<!-- End Google Tag Manager -->
<?php
}
add_action('wp_head', 'add_my_gtm_to_head', 100);
/*
* Insert Google Analytics Code in <body> tag
*/
function add_my_gtm_to_body() {
?>
<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-XXXXXX"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->
<?php
}
add_action( 'wp_body_open', 'add_my_gtm_to_body' );