GA4 tracking in Modx3 without tracking logged in users

Hi all

So a while back I mentioned I couldn’t get the isAdmin snippet to work with google analytics 4 code in Modx3.

I can’t comment on that original topic as it’s closed.

Harry suggested applying a pull request that should fix the issue of brackets within snippet calls, but I don’t know how to do that.
I’m working directly on a live server rather than a local environment.

I’ve searched the extras to see if there’s an extra to handle google analytics on modx3 but they all seem to only support up to modx 2.x

So my question is how do you all implement google analytics 4 into a modx3 site and prevent logged in users from being tracked?

Thanks in advance for any suggestions!

Andy

I believe the problem occurs because the analytics code contains square brackets which is confusing the current version of the parser in MODX - at least when the code is nested within MODX tags such as in your [[!isAdmin]] example.

What should work, I think, is if you put the analytics code straight into your snippet.

So, try creating a new snippet called analytics:

<?php
if ($modx->user->hasSessionContext('mgr')) { 
    // DO NOTHING
} else {
    echo "
            <!-- 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-54FN5RJ');</script>
            <!-- End Google Tag Manager -->
        ";
}

and call the snippet in your document head:

[[!analytics]]

YES! That works a treat - thank you so much.

1 Like

This topic was automatically closed 2 days after discussion ended and a solution was marked. New replies are no longer allowed. You can open a new topic by clicking the link icon below the original post or solution and selecting “+ New Topic”.