Tracking form submissions with Google Analytics

If you use Google Analytics to monitor web traffic on your site, you may also want to track form submissions. This article describes how to track form submissions as events with Google Analytics 4 (GA4).

Note: This article will not go into the basic usage of Google Analytics. If you are not yet familiar with Google Analytics, please refer to Google’s documentation first. The simplest way to introduce GA4 (and set it up on a WordPress site) would be to use Google’s Site Kit plugin.

Event tracking

To send an event to Google Analytics, call the gtag() function:

gtag( 'event', 'event_action', {} );

To track form submission events when sending email has successfully been completed, use the wpcf7mailsent custom DOM event:

document.addEventListener( 'wpcf7mailsent', function ( event ) {
    gtag( 'event', 'wpcf7_submission', {
        'event_category': event.detail.contactFormId,
        'event_label': event.detail.unitTag
    } );
}, false );

Inserting JavaScript into HTML

The next step is to insert the JavaScript snippet above into an appropriate place in the HTML source of frontend pages.

There are several ways to do this. We won’t go into all of them, but we will provide a coding example that uses the wp_footer action hook to insert a script element, including the above JavaScript snippet, into the footer area of pages:

add_action( 'wp_footer', function () {
?>
<script>
document.addEventListener( 'wpcf7mailsent', function ( event ) {
    gtag( 'event', 'wpcf7_submission', {
        'event_category': event.detail.contactFormId,
        'event_label': event.detail.unitTag
    } );
}, false );
</script>
<?php
}, 10, 0 );

Try embedding this into the functions.php file in your active theme. If everything has been correctly set up, you’ll see the wpcf7_submission events in the GA4 console within hours after the events tracked.

Just another contact form plugin for WordPress. Simple but flexible.