google-analyticsgoogle-analytics-apigtag.jsgoogle-analytics-sdk

Sending an event to Google Analytics doesn't work


In the header of every page I have the following integration code from Google Analytics:

<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXXXXXX-1"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'UA-XXXXXXXXX-1');
</script>

XXXXXXXXX is obviously replaced with our ID.

In the footer of a page where contact form exists, I have placed the following code:

document.addEventListener( 'wpcf7mailsent', function( event ) {
    ga( 'send', {
        hitType: 'event',
        eventCategory: 'contact-form',
        eventAction: 'contact-form-submission-mailsent',
        eventLabel: 'Contact CTA'
    });
});

The listener works well, and has been tested with console.log after a successful submit. However, no event is visible in Google Analytics under "Behavior" -> "Events". There are no other customizastion in Google Analytics, it is pretty basic.

Any help or guidance is much appreciated.


Solution

  • You can't mix Universal Analytics code and gtag code. If you have in head gtag snippet, you have to use its syntax for send an event:

    gtag('event', <action>, {
      'event_category': <category>,
      'event_label': <label>,
      'value': <value>
    });
    

    https://developers.google.com/analytics/devguides/collection/gtagjs/events