Contact Form 7 Event Tracking Script for Google Analytics & Tag Manager

Contact Form 7 is a wide used plugin for WordPress facilitating the quick and effortless publication of enquiry forms. In earlier versions of Contact Form 7 there was a great hook known as on_sent_ok through which deploy custom scripts, including scripts for triggering events for use with Google Analytics. Unfortunately, this hook is no longer operational which left many wondering how best to trigger events with Google Analytics upon the successful submission of a Contact Form 7 form.

Fortunately the guys at Contact Form 7 provided a nifty JavaScript solution for this problem, utilising the wpcf7mailsent custom DOM event which is triggered by Contact Form 7 upon successful submission of a form. While their example is super helpful, the downside is that for websites operating multiple forms, there is no way to differentiate between them. Luckily there’s a quick work around for this!

JavaScript Event Tracking Solution for Contact Form 7

The following code is the template for tracking multiple forms with a single script:

In this example, we’re using IF statements to differentiate between the different form ID. If you’re not sure of the form ID for each form, navigate to the Contact Form 7 settings within your WordPress dashboard and you should see something similar to:

How to Find ContactForm7 ID

Given the example above, you may opt to modify the code as follows:

Once you have modified the script to suit your website and form configuration, the final step is to insert the entire script into the <head> section of your website by modifying the theme’s header.php file.

(Note: If you are not using a Child Theme I strongly recommend you do so – it will avoid complications with theme updated overwriting custom scripts!)

The code in this example is configured for Universal Analytics (analytics.js) but can be easily adapted to work with legacy versions of Google Analyitcs such as ga.js or Google Tag Manager.

I hope this helps! 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *