Contact Form 7 Transformation Definition

Unlock the full potential of your WordPress contact forms with Contact Form 7’s powerful, customizable transformations. Learn more

Ceyhun Enki Aksan
Ceyhun Enki Aksan Entrepreneur, Maker

WordPress > Plugins page currently features over 50,000 plugins. Plugin recommendations can be shaped based on download and usage statistics, as well as user experiences derived from previous users’ shared implementations in various locations1.

For plugin developers2, download and usage statistics also form based on this process. Popular, favored, and most preferred plugins may become difficult to identify when specific search queries are made, as recommendations are often limited. For this reason, when a need arises, I typically first check whether a relevant plugin exists or whether one has been developed, by searching directly through wp plugin search rather than the Plugins page. Most of the results I receive are satisfactory. In this article, I will discuss the setup of tracking events for the Contact Form 7 (CF7)3 plugin—one of the most developed and widely recognized plugins when users think of a “Contact Form”—and link these events to standard events from Google Analytics, Google Ads, and Facebook Pixel. Assuming you are already using this plugin,

Form events
Form events

Contact Form 7 Form Submission Process

You can provide your visitors with a contact form for various purposes, such as selling products or collecting feedback. When a form is submitted, data will be sent to the email addresses defined in your setup or to your database via development packages. However, you may also wish to track whether the form or email submission has been processed, evaluate how users respond to forms based on different sources, and review your advertising strategy in this context. Regardless of the reasons, the key objective will be to monitor form interactions. So, how do we achieve this? In this article, in addition to the Global Site Tag function that you can directly embed on your page, I will also introduce an alternative method available through Google Tag Manager.

Contact Form 7 DOM (DOM (Document Object Model / Document Object Model) Events

The Contact Form 7 plugin provides several distinct, event-triggered DOM events that are relevant to the current state. I will go through these events in turn. However, there are a few points you should keep in mind if you wish to utilize DOM events.

  • Ensure that the DOM events are properly processed. The event handler4 will only execute when an event is triggered. Make sure your internet browser allows JavaScript execution.
  • Review the Contact Form 7 plugin settings. If the AJAX mode is inactive, events will not be triggered.
  • If there is a JavaScript error due to another plugin, the event processing will not occur. Ensure there are no JavaScript errors on the pages associated with the form.

Once you’ve completed these checks and, if necessary, implemented the required adjustments, you can proceed to the DOM events5.

CF7 DOM (Document Object Model) Events

The following actions are triggered before email submission, when the form submit button inside the form field is clicked. Previously, these actions were typically handled via on_sent_ok. However, this functionality is no longer supported within the plugin. Instead, more advanced operations can now be performed using wpcf7*6.

wpcf7invalid

Triggered when submitting the form and there is an error or missing information in the fields entered.

wpcf7spam

Triggered when submitting the form and a potential spam activity is detected.

wpcf7mailfailed

Triggered when submitting the form and an issue occurs during email sending.

wpcf7submit

Triggered during form submission, independently of the other actions.

wpcf7mailsent

Triggered during form submission if none of the above error actions occur and the form is successfully submitted.

Monitoring Actions

A user performs various actions such as page viewing, scrolling, clicking, and typing. These actions are not recorded unless explicitly marked. Similarly, the actions listed above will not be processed if they are not actively being monitored7. The code snippets below work precisely for this purpose, ensuring that the specified action is triggered whenever a relevant event occurs.

Wpcf7 wpcf7
Wpcf7 wpcf7

By default, Contact Form 7 keeps the form content within a div element. This div automatically receives the ID value corresponding to the form’s creation and a fixed wpcf7 class. By leveraging this fixed class, we can monitor actions and use addEventListener() to process all Contact Form 7 forms present on the site.

var wpcf7Sniff = document.querySelector('.wpcf7');
wpcf7Sniff.addEventListener('wpcf7submit', function(event){
    console.log('Action successful!');
}, false);

The above code will display the message ‘Action successful!’ in the console whenever it detects the ‘wpcf7submit’ event. After this stage, we can design the actions we desire as we please. For example, we can validate form inputs.

document.addEventListener('wpcf7submit', function(event) {
    var inputs = event.detail.inputs;
    for (var i = 0; i < inputs.length; i++) {
        if ('email' == inputs[i].name) {
            console.log(inputs[i].value);
            break;
        }
    }
}, false);

The above code will display the input value with the ‘email’ and ‘name’ attributes in the console during form submission. You can enhance these kinds of setups by integrating them with window.localStorage8. We can also evaluate the above events using the detail parameters.

detail.contactFormId

As I mentioned earlier, each form you create within Contact Form 7 is recorded with a unique ID. When using a form, we place a shortcut tag on the page using this ID. This ID is also used by div and form tags. We can include the form’s ID value via detail.contactFormId and the page ID where the form is placed via detail.containerPostId into our operations. For more usage options, please refer to the ‘DOM-Events’ page on the extension’s official website5. For example, let’s display the form ID in the console.

document.addEventListener('wpcf7mailsent', function(event) {
    console.log(event.detail.contactFormId);
}, false);

You can implement form-based customizations using form and page ID values. Now, to track Contact Form 7 submissions via Google Analytics, associate the wpcf7submit action with a Google Analytics goal.

Global Site Tag and Contact Form 7 Integration

GTAG (gtag.js) enables centralized data collection from both Google Analytics and Google Ads as mentioned in the relevant article, streamlining the integration and data analysis process. As per the scenario, when a form is submitted, the goal defined under Google Analytics should trigger a conversion event, as well as a conversion event in Google Ads and the Facebook Custom Pixel (using Lead instead of trackCustom).

document.addEventListener('wpcf7mailsent', function(event){
// Google Analytics
    gtag('event', 'Form Events', {
        'event_category': 'Form Submit',
        'event_label': event.detail.containerPostId
    });
// Google Ads
    gtag('event', 'conversion', {'send_to': 'AW-123456789/AbC-D_efG-h12_34-567',
        'value': 1.0,
        'currency': 'TRY'
      });
// Facebook Pixel
    fbq('trackCustom', 'Form Events', {
        event_category: 'Form Submit',
        event_label: event.detail.containerPostId
    });
}, false);

Do not forget to adjust the AW-123456789/AbC-D_efG-h12_34-567 values according to your own Google Ads conversion codes and tags. We can provide an example of the code you can directly add to your page. If you prefer to proceed through Google Tag Manager instead of the Global Site Tag, multiple options become available. Let’s start with the most practical one.

Custom html
Custom html

Log in to the Google Tag Manager panel and go to Tags > New > Choose Tag Type > select Custom HTML to set up the above action as desired9. Of course, you’ll need to separate and set up Google Analytics and Google Ads in this situation10. We can illustrate our dataLayer configuration for Analytics and Ads as follows:

document.addEventListener( 'wpcf7mailsent', function( event ) {
        dataLayer.push({
          'event' : 'wpcf7submitted',
          'CF7PostID' : event.detail.containerPostId
        });
     }, false );

For the conversion tracking setup, proceed via Variables > User Defined Variables > New > Custom Event to define the wpcf7mailsent event. Then, create the corresponding Google Analytics Event and Google Ads snippets as triggers for this event. For Facebook Custom Pixel, you can use the Custom HTML trigger with the fbq function as well. As I mentioned, some familiarity with JavaScript, Google Analytics, Ads, and Tag Manager is required, along with appropriate editing permissions.

*[DOM]: Document Object Model
*[GTAG]: Global Site Tag

Footnotes

  1. Editorial Staff. (2018). Beginner’s Guide: How to Choose the Best WordPress Plugin
  2. WordPress Plugin Handbook
  3. Contact Form 7. WordPress Plugin
  4. Overview of events and handlers. MDN web docs
  5. DOM events. Contact Form 7 2
  6. on_sent_ok Is Deprecated. Contact Form 7
  7. EventTarget.addEventListener. MDN web docs
  8. Window.localStorage. MDN web docs
  9. James. (2017). Goal Tracking for Contact Form 7 (CF7) with DOM Events & Google Tag Manager
  10. Chris Berkley. (2017). Contact Form 7 Event Tracking with Google Tag Manager