Adding Google Analytics tracking to WordPress Gutenberg block editor elements

I’m trying to set up GA4 analytics using Google Tag Manager on a WordPress site that uses the Gutenberg block editor. I’m having some difficulty tracking user interactions with clickable elements like buttons and links created with Gutenberg.

I’m unsure about how to add unique identifiers or classes to these elements for better tracking. When I use the Gutenberg editor to create links or buttons, I don’t find clear options for adding custom IDs or tracking attributes.

Has anyone managed to successfully track clicks on elements made with Gutenberg? What strategies work best for making these elements visible to Google Analytics? I would appreciate any tips or methods!

I solved this with a custom JavaScript script that works with GTM. The script automatically detects Gutenberg blocks and adds data attributes based on their content or position. No need to manually add classes to every button or link through the editor. For buttons, I target the .wp-block-button class - it works reliably across themes. When someone clicks these elements, the script pushes custom events to the dataLayer. You get interaction tracking without touching each block manually. Another trick: use the block editor’s HTML mode when you need precise control. Switch any block to HTML view and add custom data attributes straight into the markup. It’s more technical but gives you exact tracking for important conversion elements.

I experienced similar difficulties when trying to implement GA4 tracking in Gutenberg. What proved effective for me was utilizing the ‘Additional CSS Classes’ option within the block settings, allowing me to assign custom classes such as ‘track-click’ to the buttons and links I created. Additionally, I configured triggers in Google Tag Manager to monitor these specific elements. Certain blocks also support adding HTML anchors, offering a way to include ID attributes for more accurate tracking. Consistency in your naming conventions is key, alongside thorough testing to ensure the reliability of the data gathered.