Hi dear, it’s a please for me in first time answering something here, while being also the first to answer your question.
I think the solution I’ll propose here is better than what you have mentioned, but I don’t know if this is really the best one. I’ll share it and let’s see what the community experts say.
In the theme/functions.php file, find the line where it loads/register the “setup” and “filters” php files, add a new one, let’s call it “analytics”, so that block of code will look like this:
collect(['setup', 'filters', 'analytics'])
->each(function ($file) {
[...]
Then, I created an environment variable called “GTM_ID” on my .env file:
#GOOGLE TAG MANAGER (GTM) ID
GTM_ID=GTM-XXXXXX
And finally, our analytics.php file, that includes the scripts required, on wp_head and wp_body_open using add_action, loading the GTM_ID from the .env file:
<?php
/**
* Analytics helpers.
*/
add_action(
'wp_head',
function (): void {
if(getenv('GTM_ID')){
?>
<!-- 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','<?= env('GTM_ID')?>');</script>
<!-- End Google Tag Manager -->
<?php
}
},
1,
0
);
add_action(
'wp_body_open',
function (): void {
if(getenv('GTM_ID')){
?>
<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=<?= env('GTM_ID')?>"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->
<?php
}
},
1,
0
);
Hope this get you to a good point!
Thanks,
Matt.