Search code examples
wordpressanalyticsevent-trackinggtag.js

addEventListener for gtag event tracking to Wordpress page


I want to add Analytics event tracking to a link on a Wordpress page. The following code is added to the end of the body section. If I inspect the page with developer tools in Chrome, I can see that the EventListener is there for my a tag. But the event doesn't get sent to Analytics...

document.addEventListener("FreeDownloadEventTracking", function(event) { 
    jQuery('div.free-download a').click(function() {
        gtag('event', 'free plugin', {
          'event_category' : 'downloads',
          'event_label' : 'wordpress.org plugin link'
        });
    }); 
});

Can anybody tell me what's the problem here? Thanks!


Solution

  • You are adding a jQuery click event inside a FreeDownloadEventTracking event, which I presume doesn't exist.

    The page would need to trigger FreeDownloadEventTracking for your click event to be added to the download link.

    I would suggest replacing FreeDownloadEventTracking with DOMContentLoaded so your click event is added to div.free-download a when the DOM is loaded. Then clicking the free download link will trigger gtag