I have a problem with sending custom events to GA4 using GTM. The problem is the event attributes are dynamically pushed using dataLayer. I can't seem to find a way to reliably forward the attributes to GA4.
So we have a bit of javascript code that runs gtag('event', 'make_noise', {instrument: 'gituar'})
.
Then we have a GTM tag "Google Analytics: GA4 Event" that is triggered by "make_noise" custom event above. Now, this works - we can see "make_noise" event being forwarded to our GA4 property.
What I can't figure out is how to forward the "instrument" attribute from the custom event down to GA4. I can't just add instrument: guitar attribute to the GTM tag, as the value of instrument attribute is dynamic. It can be called with wide variety of values, so I should really be able to use whatever is sent via javascript code and forward that to GA4.
So I created a "Data Layer Variable" that reads "dataModel.instrument" and I used this variable in my GA4 Event tag. It worked (dynamic "instrument" attribute is forwarded as expected), but, when I send two events in short timespan, e.g.:
gtag('event', 'make_noise', {instrument: 'gituar'});
gtag('event', 'do_stuff', {foo: 'bar'});
the "make_noise" event on the GA4 side no longer has the "instrument" attribute. It's undefined. Presumably because variable reads last state of dataModel (where only "foo" is defined).
How do I solve this?
Think of your problem as if a client uses the search event and has a dynamic 'search_term' parameter within the event:
You have your dataLayer in place
Your GTM is setup:
Set up Analytics under custom events (you should add 'make_noise') and custom definition (you should add 'instrument')
That should be it ...
Edit:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With