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! 🙂

2 thoughts on “Contact Form 7 Event Tracking Script for Google Analytics & Tag Manager

  • Hey Chris,

    Thanks for putting this together. On my client’s WordPress they have Divi Shortcodes listed, instead of ID numbers for each contact form. So for example one form has [DiviShortcode id=”11504″] listed.

    In this case, do you know where/how I would get an ID to use here, or would it simply be “11504”?

    Thanks for any help!

    • Hi Matt,

      Is the form plugin definitely ContactForm7? You should see a shortcode in the format as per the screenshot above (i.e. [contact-form-7 id=”XXX” title=”Form Title”]).

      If you’re seeing a Divi shortcode it sounds like they’re using Elegant Themes’ Divi Form Builder; I could be wrong though!

      Thanks.

Leave a Reply

Your e-mail address will not be published. Required fields are marked *