Skip to content

Google AdsPublished 16 min read

Contact Form 7 Google Ads Conversion Tracking with GTM

How to count only real, successful Contact Form 7 submissions in Google Ads and GA4 using the wpcf7mailsent event, a small GTM listener and enhanced conversions.

Muhammad Qitmeer, founder of Augere Labs
Muhammad Qitmeer
Co-founder and CEO, Augere Labs
Share

For Contact Form 7 Google Ads conversion tracking, listen for the wpcf7mailsent DOM event with a small Custom HTML tag in Google Tag Manager, push a dataLayer event with the form ID and the visitor's email, and fire your Google Ads conversion tag and GA4 generate_lead event from that. wpcf7mailsent only fires when the submission passed validation and spam checks and the mail went out, so invalid, spam and failed submissions never count. Do not use a click trigger or GTM's built-in form submission trigger for Contact Form 7.

This is for agency owners, PPC managers and developers who look after WordPress client sites that run Contact Form 7 (CF7). It covers every event CF7 fires and what is in event.detail, a listener you can paste into GTM, why wpcf7mailsent is the right one, what happened to on_sent_ok, the redirect approach, enhanced conversions using the email field, spam and reCAPTCHA behavior, multiple forms, and how to test it all before a client's budget depends on it.

Why don't GTM click and form triggers work with Contact Form 7?

Contact Form 7 submits through JavaScript. When someone clicks Send, CF7 stops the normal browser submit, sends the data to its own REST endpoint in the background, then shows the response message on the same page. There is no page load and no thank-you URL by default.

  • Click triggers. A click on the submit button fires whether the form is valid or not. Empty fields, a bad email, a spam rejection: all of them count as a conversion. This is the most common reason a CF7 site shows more Google Ads conversions than real leads.
  • GTM Form Submission trigger. CF7 calls preventDefault() on the submit event. With "Check Validation" turned on, GTM sees the default as prevented and the trigger never fires. With it turned off, it fires on every attempt, valid or not. Neither tells you the server accepted the lead.
  • Element visibility on the success message. It can work, but the response box is used for errors too, so you end up matching on CSS classes or message text that a theme, translation or plugin update can change.

CF7 already tells the page exactly what happened through DOM events. Use them. If you need the general pattern for other form plugins, our Google Tag Manager form tracking guide covers it.

What DOM events does Contact Form 7 fire?

Every CF7 event is a CustomEvent dispatched on the form element with bubbles: true, so you can listen on document and catch every form on the page. The names below come from the current plugin source (6.x). After the server responds, CF7 fires one result event, then always fires wpcf7submit.

EventWhen it firesServer statusCount as a conversion?
wpcf7beforesubmitJust before the request is sentnone yetNo
wpcf7invalidA field failed validationvalidation_failedNo
wpcf7unacceptedA required acceptance checkbox was not tickedacceptance_missingNo
wpcf7spamA spam check rejected the submissionspamNo
wpcf7abortedCode hooked into the send process stopped itabortedNo
wpcf7mailsentMail was sent successfullymail_sentYes
wpcf7mailfailedEverything passed but sending the mail failedmail_failedNo, but alert on it
wpcf7submitAfter every completed request, whatever the resultanyNo

There are also wpcf7reset (after the form resets) and wpcf7statuschanged (on every status change). You do not need either for conversion tracking.

What is in event.detail?

The submit events carry a detail object with these properties:

  • contactFormId. The form's numeric post ID, as a number.
  • unitTag. A string that identifies this instance of the form on the page, such as wpcf7-f123-p45-o1: form 123, on post 45, first form rendered on the page.
  • containerPostId. The ID of the page or post that contains the form. Useful when the same form sits on many landing pages.
  • inputs. An array of { name, value } objects, one per submitted field. CF7's hidden fields (names starting with an underscore) are left out.
  • formData. The raw FormData object.
  • status. The status class, for example sent, invalid or spam.
  • apiResponse. The full JSON response from the server, including apiResponse.status (such as mail_sent) and apiResponse.message.
  • pluginVersion and contactFormLocale. The CF7 version and form locale.

Why is contactFormId not the ID in my shortcode?

Since CF7 5.8, new shortcodes use a short hash, like [contact-form-7 id="a1b2c3d" title="Contact form 1"]. The contactFormId in the event is still the numeric post ID. If your trigger compares against the hash, it never matches. Find the numeric ID in the admin: open the form under Contact, and the edit URL ends in something like admin.php?page=wpcf7&post=123&action=edit. The post value is what the event reports. Or submit the form once in GTM Preview and read it from the dataLayer.

Should I use wpcf7mailsent or wpcf7submit?

Use wpcf7mailsent. The name trips people up: wpcf7submit sounds like "the form was submitted," but it fires after every request, including validation errors and spam rejections. Tracking it gives you the same inflated numbers as a click trigger.

wpcf7mailsent fires only when the server returned mail_sent, which means the submission passed validation, the acceptance check, the spam filters, any upload handling and any code that can abort it, and then the mail was sent. That is as close to "a real lead arrived" as the browser can know.

Two edge cases to know:

  • Skipped mail still counts as sent. If the form's Additional Settings include skip_mail: on or demo_mode: on, CF7 skips sending but still returns mail_sent, so wpcf7mailsent fires. Some sites use skip_mail on purpose because a CRM integration takes the data. That is fine. But a form left in demo mode after testing will keep logging conversions while nobody gets the emails.
  • Mail failures are real people. wpcf7mailfailed means a real visitor filled in the form and saw an error, usually because the server cannot send mail. Do not count it as a conversion, but do send it to GA4 as a separate event so you notice. A site with broken SMTP can lose leads for weeks before anyone checks the inbox.

What replaced on_sent_ok in Contact Form 7?

Older tutorials tell you to put on_sent_ok: "gtag(...)" or on_sent_ok: "location = '/thank-you/';" in the form's Additional Settings tab. CF7 deprecated on_sent_ok and its sibling on_submit in 2017 and stopped running them in version 5.0. The replacement is the wpcf7mailsent DOM event.

If you inherit a site that still has on_sent_ok in Additional Settings, it does nothing. The CF7 editor flags it as a deprecated setting. Delete it so the next person does not assume it is tracking, and add the listener below instead.

The GTM listener for Contact Form 7

Create a Custom HTML tag in GTM named something like "CF7 listener". It listens for the CF7 events and turns them into dataLayer events. Fire it on the Initialization - All Pages trigger, or All Pages. Because it listens on document, it only has to load before the visitor clicks Send.

<script>
  (function () {
    // Guard: never attach the listener twice on the same page
    if (window.cf7ListenerAttached) { return; }
    window.cf7ListenerAttached = true;
    window.dataLayer = window.dataLayer || [];
  
    function getField(inputs, name) {
      for (var i = 0; i < inputs.length; i++) {
        if (inputs[i].name === name) { return String(inputs[i].value); }
      }
      return '';
    }
  
    document.addEventListener('wpcf7mailsent', function (event) {
      var d = event.detail || {};
      var inputs = d.inputs || [];
      var email = getField(inputs, 'your-email').trim().toLowerCase();
  
      window.dataLayer.push({
        event: 'cf7_mail_sent',
        cf7_form_id: String(d.contactFormId),
        cf7_unit_tag: d.unitTag,
        cf7_page_id: String(d.containerPostId),
        cf7_email: email
      });
    }, false);
  
    var problems = ['wpcf7invalid', 'wpcf7unaccepted', 'wpcf7spam', 'wpcf7aborted', 'wpcf7mailfailed'];
    problems.forEach(function (name) {
      document.addEventListener(name, function (event) {
        var d = event.detail || {};
        window.dataLayer.push({
          event: 'cf7_not_sent',
          cf7_form_id: String(d.contactFormId),
          cf7_result: d.apiResponse ? d.apiResponse.status : name
        });
      }, false);
    });
  })();
  </script>

Notes on the code:

  • The field name. your-email is the name in CF7's default form. Many forms use a different one. Open the form's Form tab and look for the email tag, for example [email* work-email], then change the name in getField.
  • Read values from event.detail, not the page. After mail_sent, CF7 resets the form right after dispatching the events. A DOM Element or CSS selector variable that reads the email input can come back empty depending on when your tag evaluates it. event.detail.inputs is a copy taken before the reset, so it is safe.
  • Form ID as a string. Converting it to a string keeps GTM trigger conditions simple, since you compare text like 123.
  • No personal data in the failure event. cf7_not_sent only carries the form ID and result, so you can send it to GA4 without leaking what people typed.
  • Plain ES5. The code avoids newer syntax so it runs in GTM Custom HTML and older browsers without surprises.

Then build the GTM pieces:

  1. Data Layer Variables. Create cf7_form_id, cf7_page_id, cf7_email and cf7_result.
  2. Custom Event trigger. Event name cf7_mail_sent. Leave regex off. Add a condition on cf7_form_id if only some forms are leads.
  3. Google Ads Conversion Tracking tag. Your conversion ID and label, fired by that trigger. Make sure a Conversion Linker tag fires on all pages so the gclid from the landing page is stored.
  4. GA4 event tag. Event name generate_lead, fired by the same trigger. Add a form_id parameter from cf7_form_id if you want to split reporting by form. Mark generate_lead as a key event in GA4.
  5. Optional diagnostics tag. A GA4 event such as cf7_not_sent on a Custom Event trigger for cf7_not_sent, with form_id and result parameters. Do not mark it as a key event.

generate_lead is the event Google documents for lead forms, with optional value, currency and lead_source parameters. See Google's GA4 event reference. If value is set, currency is required. If you are deciding names across many client properties, our GA4 key events and naming plan helps keep them consistent.

How do I track multiple Contact Form 7 forms separately?

Most client sites have more than one form: a contact form, a quote form, a newsletter box built with CF7, maybe a careers form. Only some of them are leads you want Google Ads to bid on.

  • Filter by form ID. In the cf7_mail_sent trigger, add the condition cf7_form_id matches RegEx ^(123|456)$ for the lead forms only. Anchor the pattern so 12 does not also match 123.
  • Different conversion actions per form. Create one trigger per form, or one trigger plus a Lookup Table variable that maps cf7_form_id to a conversion label. Keep the newsletter and careers forms out of Google Ads entirely, or make them secondary conversions so they do not drive bidding.
  • Same form on many pages. Use cf7_page_id to tell which landing page produced the lead. In GA4 the page location already does this, but the ID survives URL changes.
  • Same form twice on one page. A form in the content and the same form in the footer share a contactFormId. The unitTag differs, ending in -o1 or -o2 based on render order. Use it if you need to know which copy was used.

How do I send the email field for Google Ads enhanced conversions?

Enhanced conversions send a hashed version of the email with the conversion, which helps Google match leads it would otherwise lose to cookie limits. With the listener above, the email is already in the dataLayer as cf7_email, normalized to lowercase with spaces trimmed.

  1. Turn it on in Google Ads. In the conversion action settings, enable enhanced conversions and choose Google Tag Manager as the method.
  2. Create a User-Provided Data variable. In GTM, choose Manual configuration and set Email to your cf7_email Data Layer Variable. Add phone too if the form collects it, in E.164 format such as +14155550123.
  3. Attach it to the conversion tag. In the Google Ads Conversion Tracking tag, enable user-provided data and select the variable.

GTM hashes the values before sending, so you pass plain text. Google's setup steps are in Set up enhanced conversions for web using Google Tag Manager. Avoid the CSS selector method for CF7, for the reset reason covered above. Avoid automatic detection too: it guesses from the page, and on CF7 the field may already be empty.

Two things to check. If the site runs consent mode, Google only uses this data when ad_user_data is granted, so a broken banner can quietly switch enhanced conversions off. Our Consent Mode v2 implementation guide covers that. For the full setup, diagnostics and timing, see the enhanced conversions setup guide.

Should I redirect Contact Form 7 to a thank-you page instead?

A thank-you page has real benefits. It gives you a URL to report on, a place to set expectations or show a booking calendar, and a fallback that people outside your team understand. The downside: if the conversion fires on the page view alone, every refresh, bookmark, back-button visit and crawler hit counts. Thank-you pages also get indexed and found through site search.

If the client wants a redirect, keep the conversion tied to the event, not the URL. Two ways:

Option 1: fire on the event, then redirect

Add the redirect to the same listener after the dataLayer push, with a short delay so the tags have time to send:

document.addEventListener('wpcf7mailsent', function (event) {
    // dataLayer push from the listener above runs first
    if (String(event.detail.contactFormId) === '123') {
      setTimeout(function () {
        window.location.href = '/thank-you/';
      }, 600);
    }
  }, false);

This is simple, but it is a race. On a slow phone connection the browser can leave the page before the requests finish. Raising the delay helps, at the cost of a visible pause.

Option 2: set a flag, confirm on the thank-you page

The listener stores a one-time flag, then redirects right away. A Custom HTML tag on the thank-you page checks the flag, clears it, and pushes the conversion event. A refresh or a direct visit finds no flag and fires nothing.

// In the CF7 listener, inside the wpcf7mailsent handler
  try {
    sessionStorage.setItem('cf7_lead', JSON.stringify({
      form: String(event.detail.contactFormId),
      email: email
    }));
  } catch (e) {}
  window.location.href = '/thank-you/';
  
  // Custom HTML tag fired on the thank-you page only
  (function () {
    var raw = null;
    try {
      raw = sessionStorage.getItem('cf7_lead');
      sessionStorage.removeItem('cf7_lead');
    } catch (e) {}
    if (!raw) { return; }
    var lead = JSON.parse(raw);
    window.dataLayer = window.dataLayer || [];
    window.dataLayer.push({
      event: 'cf7_mail_sent',
      cf7_form_id: lead.form,
      cf7_email: lead.email
    });
  })();

Wrap the second part in script tags in GTM. If you use this pattern, do not also push cf7_mail_sent on the form page, or each lead counts twice. The email sits in session storage for about a second. If the client's privacy policy rules that out, store only the form ID and skip enhanced conversions, or use Option 1.

Some plugins add a redirect field to CF7. They work the same way under the hood, listening for wpcf7mailsent, so the same race applies. Check how a plugin fires its redirect before trusting it with tracking.

Will spam, reCAPTCHA or Akismet failures count as conversions?

Not with wpcf7mailsent. CF7 runs its spam checks on the server before sending mail. If any of them flags the submission, the response status is spam, the browser gets wpcf7spam, and wpcf7mailsent never fires. That covers:

  • reCAPTCHA v3. CF7's built-in integration marks the submission as spam when the token is missing or the score is below the threshold.
  • Cloudflare Turnstile. CF7 has a built-in Turnstile module too, and a failed check is treated as spam.
  • Akismet. If Akismet is configured for the form and flags the content, it is spam.
  • Disallowed comment keys. CF7 checks WordPress's disallowed list, and a match is spam.

What it does not protect you from is spam that passes the checks. A human filling in the form by hand, or a bot that beats the captcha, still produces a real mail_sent and a real conversion. If a client's Google Ads account shows a surge of cheap form conversions from Performance Max or Display, that is usually low-quality traffic passing the filters, not a tracking bug. The fix is on the lead quality side: send qualified-lead stages back from the CRM through an offline conversion import and let bidding optimize for those.

One thing to watch with reCAPTCHA v3: when the script cannot load, for example because a consent tool blocks it until the visitor accepts, the token is empty and CF7 rejects real people as spam. You will see this as cf7_not_sent events with result spam in GA4 while the client complains that the form "stopped working." That is the diagnostics tag paying for itself.

Why is my Contact Form 7 conversion firing twice?

Double counting on CF7 almost always comes from one of these:

  • Two tracking paths. A GTM conversion tag plus a conversion imported from GA4, both set as primary for the same action. Or a plugin that sends conversions while GTM does too. Pick one source per conversion action.
  • The listener attached twice. The Custom HTML tag fires on two triggers, or is pasted into GTM and also into the theme's footer. The guard flag in the code above prevents duplicate pushes from the GTM copy, but a second hard-coded copy has no guard. Search the theme and any "header and footer scripts" plugin for wpcf7mailsent.
  • A thank-you page plus the event. The event fires the conversion and the thank-you page view fires it again.
  • The conversion counted as Every instead of One. For leads, set the Google Ads conversion action to count One per click, so a person who submits twice is one conversion.

CF7 itself will not fire wpcf7mailsent twice for one click. It ignores a new submit while one is in progress. Our fix page on Google Ads counting conversions twice walks through finding the duplicate source.

When do Contact Form 7 events not fire at all?

  • The plugin's JavaScript did not load or run. If a minify or "delay JavaScript" setting breaks CF7's script, or a theme dequeues it, CF7 falls back to a normal page-reload submission. The lead may still be sent, but no DOM events fire. Check the console for CF7 errors such as "wpcf7 is not defined."
  • The REST request failed. CF7 submits to the WordPress REST API. If a security plugin or firewall blocks /wp-json/contact-form-7/, or the visitor goes offline, the request fails, no result event is dispatched and the visitor sees a spinner or an error.
  • The form is nested inside another form. Some page builders wrap content in a form tag. CF7 detects this and replaces the form with an error message.
  • Payment forms. CF7's Stripe integration can return a payment_required status first. The mail is only sent, and wpcf7mailsent only fires, after the payment step completes.
  • GTM blocked or delayed. If the listener tag is held back by consent settings that need a consent type the visitor never grants, it never attaches. The listener itself does not send data anywhere, so it is usually safe to fire it without consent and let the Google tags handle consent themselves.

For a more general checklist, see GA4 form submissions not tracked.

How to test Contact Form 7 conversion tracking

  1. Open GTM Preview on a page with the form and confirm the CF7 listener tag fired on page load.
  2. Submit an empty form. You should see cf7_not_sent with result validation_failed, and no conversion tag.
  3. Submit a valid form with a test email you control. You should see cf7_mail_sent, with the numeric form ID and the email in the dataLayer, and the Google Ads and GA4 tags fired once each.
  4. Check the user-provided data. In the Google Ads tag's details in Preview, confirm the email value is populated, not empty.
  5. Check the inbox. Make sure the mail arrived. If the event fired but no email came, look for skip_mail or demo_mode in Additional Settings.
  6. Check GA4 DebugView for generate_lead with your parameters.
  7. Watch Google Ads diagnostics. The conversion action should show recent activity within a day or so. Enhanced conversions diagnostics take longer to report.
  8. Remove test leads from the client's CRM so they do not skew sales follow-up.

If you need to test whether spam blocking stays out of your numbers, submit text that matches an entry in the WordPress disallowed list. It should produce cf7_not_sent with result spam.

Getting it fixed for a client

Most CF7 tracking we see on inherited accounts has the same three problems: a click trigger or wpcf7submit counting every attempt, a leftover on_sent_ok that does nothing, and enhanced conversions reading an empty field. Each one is a small change, but each one changes what Google Ads bids on. If you want a second pair of eyes on a client's setup before you rebuild it, request a free tracking check and we will tell you what is counting, what is not, and why.

Just one quick fix, not a whole account? Our founder takes small fixed-price jobs on Fiverr: Google Ads conversion tracking fix

Frequently asked questions

What is the best event for Contact Form 7 conversion tracking?

Use wpcf7mailsent. It fires only when the submission passed validation and spam checks and the mail was sent. wpcf7submit fires after every attempt, including errors and spam, so it overcounts.

Does on_sent_ok still work in Contact Form 7?

No. It was deprecated in 2017 and stopped working in Contact Form 7 5.0, along with on_submit. Remove it from Additional Settings and use a listener for the wpcf7mailsent DOM event instead.

Why does my GTM trigger not match my Contact Form 7 form ID?

Since version 5.8, shortcodes use a hash ID, but event.detail.contactFormId is the numeric post ID. Find it in the form's edit URL (the post parameter) or read it from the dataLayer in GTM Preview.

Will reCAPTCHA or Akismet rejections count as Google Ads conversions?

Not if you track wpcf7mailsent. Submissions rejected by reCAPTCHA, Turnstile, Akismet or the disallowed list return a spam status and fire wpcf7spam instead, so no conversion is sent.

How do I pass the email from Contact Form 7 to enhanced conversions?

Read it from event.detail.inputs in your wpcf7mailsent listener, push it to the dataLayer, and map that variable as Email in a User-Provided Data variable. Do not read the input from the page, because CF7 resets the form after sending.

Muhammad Qitmeer

Written by

Muhammad Qitmeer, founder of Augere Labs

Augere Labs is the white-label tracking partner behind marketing agencies. If a client account has numbers you don't trust, I'm happy to look at it with you and tell you straight what's wrong.

Connect on LinkedIn