I’d written earlier about how to load the Google Tag Manager only on specific pages, and I’d mentioned there that we could ensure that certain tags would only fire when the user was or wasn’t logged into the CMS. A great use-case scenario for this is when we don’t want our Google Analytics code to load when we ourselves are visiting the page. Even though there are ways to exclude our visits, like with the IP address for example, these aren’t always reliable. But by detecting the login status of a visitor, a lot of sites can get extremely accurate results.
How HTML Code Changes for Logged in Users
The WordPress HTML code is different for anonymous and logged in users. The differences run pretty deep, even if it’s not easily visible on the outside. Most websites don’t show any external differences between the two versions, apart from the “admin” bar that’s often present on the top – and even with that, some might choose to disable it.
But when you dive into the code, you can see the real difference. For example, here’s the HTML code of my website WP-Tweaks when I examine the source after logging in:
Creating the GTM Variable
To get started, we need to use GTM to create a variable that reflects whether or not we’re logged in. We do this by checking for the presence of the above code. Here’s how to do it.
When you log into GTM, click the “Variable” section on the left-hand side like this:
On the right-hand side pane, you’ll see a number of pre-defined variables. What we want however, is a new user-defined variable. For this, scroll down and click “New”. This will bring up the variable configuration screen. You need to enter the following details:
Choose to create a new variable based on the DOM Element as shown above. Then choose “CSS Selector” and for the actual element, type in “body.logged-in” and input “class” as the “Attribute name” field. Once all this is done, save the variable and you’re done.
Using the Variable in a Trigger
Creating a variable by itself doesn’t matter much, unless you use it in a trigger. Specifically, if the variable turns out to be “null”, it means that GTM didn’t find the HTML code and the user is anonymous. If it’s anything else, it means that the user has logged in.
In the Trigger configuration screen below, you can see that I’ve used the new variable to check if a user is logged in or not:
Once you’ve created this trigger, you can apply it to a specific tag in GTM to isolate the conditions under which you want the tag to run. Using this, I’ve personally created a lot of combinations of triggers that determine precisely when my code will run. It’s very convenient!
I’m a NameHero team member, and an expert on WordPress and web hosting. I’ve been in this industry since 2008. I’ve also developed apps on Android and have written extensive tutorials on managing Linux servers. You can contact me on my website WP-Tweaks.com!