I am preparing to switch a site that's using Google Analytics 4 from using gtag() over to Google Tag Manager (server-side). One of the things I would like to do is set custom dimensions after initial page load.
Basically I'd like to do something like:
- visitor lands on site, starts clicking around and doing stuff
- some amount of time passes while they do more stuff and view more pages
- they do something that puts them into a group that I want to track, such as "Group A" or "Group B". Or maybe they do nothing of particular note, but I decide to put them in one of the above groups, just because I feel like it
- Now I want to tell google that this user is in that group, and they will stay in that group for their entire visit (hence the custom dimension instead of just normal event tracking)
In my case the key issue seems to be that step 3 above can happen at any point in time, such as while the user is scrolling around etc, and the page's GTM config has already run (so the data layer has already been defined and initialized).
Can I still simply push my dimension onto the data layer, and analytics will pick it up and "remember" that these users are in those groups? What is the proper syntax for pushing a dimension?
I've read through mountains of how-to's online, watched videos, as well as sifted through stack overflow questions/answers like this one and this one, but none seem to address my particular situation (or maybe it's late in the day and I missed the right one).
Here's what I ended up doing, which seems to be working so far.
First, I push a custom event onto the data layer variable, with a custom data layer variable for the dimension I want to track. For example, replace 'DimensionName' and 'DimensionValue' below with whatever you want your name and value to be:
Then I prepared GTM to receive that custom variable ("cd_DimensionName"):
{{cd_DimensionName}}Then I told GTM to watch for a custom event called "setCustomDimension":
{{DimensionName}}Finally, make sure to set the variable up in google analytics as normal (Admin > Data display > Custom definitions).
This is working for me, but I'm open to suggestions on a less convoluted method.