How to Track WP Forms with Google Analytics 4 and Tag Manager

May 27, 2024 at 4:02:26 PM

TL;DR The article provides a guide on tracking WP forms using Google Analytics 4 (GA4) and Google Tag Manager (GTM). It covers methods based on whether the form uses AJAX. For AJAX forms, it explains creating an AJAX listener with custom HTML in GTM, setting up triggers, and extracting form IDs. For non-AJAX forms, it describes using built-in GA4 form tracking and GTM's form submission trigger. The article also includes steps for testing the setup and finding form submission data in GA4 reports.

How to Track WP Forms with Google Analytics 4 and Tag Manager

Struggling to track WP forms on your site? This guide offers multiple methods for tracking WP forms with Google Analytics 4 (GA4) and Google Tag Manager (GTM), tailored to the type of form you have. Here's a breakdown:

Assumptions:

  • GA4 is installed on your website using GTM.
  • Familiarity with creating tags, triggers, and variables in GTM.

Determine the Method:

  • AJAX Forms: If the page doesn't refresh upon form submission, use the AJAX method.
  • Non-AJAX Forms: If the page refreshes, use GA4 built-in tracking or GTM's built-in Form Submission trigger.

AJAX Method:

  1. Create AJAX Listener:

    • Use a custom HTML tag in GTM to listen for AJAX requests and push data to the Data Layer.
    • Example code for AJAX listener:
      <script id="gtm-jq-ajax-listen" type="text/javascript">
      (function() {
          'use strict';
          var $;
          var n = 0;
          init();
          function init(n) {
              if (typeof jQuery !== 'undefined') {
                  $ = jQuery;
                  bindToAjax();
              } else if (n < 20) {
                  n++;
                  setTimeout(init, 500);
              }
          }
          function bindToAjax() {
              $(document).bind('ajaxComplete', function(evt, jqXhr, opts) {
                  var fullUrl = document.createElement('a');
                  fullUrl.href = opts.url;
                  var pathname = fullUrl.pathname[0] === '/' ? fullUrl.pathname : '/' + fullUrl.pathname;
                  var queryString = fullUrl.search[0] === '?' ? fullUrl.search.slice(1) : fullUrl.search;
                  var queryParameters = objMap(queryString, '&', '=', true);
                  var headers = objMap(jqXhr.getAllResponseHeaders(), '\n', ':');
                  dataLayer.push({
                      'event': 'ajaxComplete',
                      'attributes': {
                          'type': opts.type || '',
                          'url': fullUrl.href || '',
                          'queryParameters': queryParameters,
                          'pathname': pathname || '',
                          'hostname': fullUrl.hostname || '',
                          'protocol': fullUrl.protocol || '',
                          'fragment': fullUrl.hash || '',
                          'statusCode': jqXhr.status || '',
                          'statusText': jqXhr.statusText || '',
                          'headers': headers,
                          'timestamp': evt.timeStamp || '',
                          'contentType': opts.contentType || '',
                          'response': (jqXhr.responseJSON || jqXhr.responseXML || jqXhr.responseText || '')
                      }
                  });
              });
          }
          function objMap(data, delim, spl, decode) {
              var obj = {};
              if (!data || !delim || !spl) {
                  return {};
              }
              var arr = data.split(delim);
              var i;
              if (arr) {
                  for (i = 0; i < arr.length; i++) {
                      var item = decode ? decodeURIComponent(arr[i]) : arr[i];
                      var pair = item.split(spl);
                      var key = trim_(pair[0]);
                      var value = trim_(pair[1]);
                      if (key && value) {
                          obj[key] = value;
                      }
                  }
              }
              return obj;
          }
          function trim_(str) {
              if (str) {
                  return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
              }
          }
      })();
      </script>
      
    • Configure the tag in GTM and set triggers based on your needs (all pages or specific pages).
  2. Only Trigger Event on WP Forms:

    • Inspect the page to find a unique identifier for WP forms in the dataLayer.
    • Create a Data Layer Variable and a custom trigger in GTM to fire only for WP forms.
  3. Extract WP Form ID:

    • Use custom JavaScript in GTM to extract the form ID from the dataLayer.
    • Example code:
      function(){
          var input = {{dlv - attributes.response.data.confirmation}};
          var regex = /id="wpforms-confirmation-(\d+)"/;
          var match = regex.exec(input);
          if (match && match[1]) {
              return match[1];
          }
      }
      
  4. Create GA4 Event Tag:

    • Configure a GA4 event tag in GTM with the necessary parameters and triggers.
    • Include the measurement ID and event name (e.g., form_submission).
  5. Create Custom Dimension for Form ID in GA4:

    • In GA4, create an event-scoped custom dimension for the Form ID.
  6. Test the New Event:

    • Preview the GTM container and submit the form to ensure the event fires correctly.
    • Check DebugView in GA4 for the event and parameters.

Alternative Methods:

  1. Using Built-in GA4 Form Tracking:

    • Enable enhanced measurements and "Form Interactions" in GA4.
    • Note: This method may not be precise and could capture unwanted events.
  2. Using Built-in Form Submission Trigger in GTM:

    • Enable form variables in GTM.
    • Create a form submission trigger specific to WP forms.
    • Configure a GA4 event tag with the necessary parameters and triggers.

Finding Form Submission Data in GA4:

  1. Built-in Standard Report:

    • Use the Events report in GA4 and filter by the event name form_submission.
    • Break down data by Form ID.
  2. GA4 Explorations:

    • Create a custom exploration in GA4 with dimensions and metrics relevant to form submissions.

Final Thoughts:

  • Use only one tracking method to avoid duplicate data.
  • Regularly test and verify your setup to ensure accurate tracking.

Q&A

Have more questions on this topic? Ask our AI assistant for in-depth insights.

The Only Digital Marketing Feed You'll Ever Need.

Stay informed your way. Tailored updates when and how you want them. 100% Free.

10,000+ Users

500+ Sources

1000+ Tools

Or

Related Posts

Google Analytics 4 boosts data completeness and proactive issue detection for marketers

Google Analytics 4 boosts data completeness and proactive issue detection for marketers

Google
Google

Official Source

Official Source

Google is a Official Source. The source has been verified by Swipe Insight team.

Official Source
Google Tag Manager Adds New Diagnostic Alerts and Dismissal Options for Users

Google Tag Manager Adds New Diagnostic Alerts and Dismissal Options for Users

Google
Google

Official Source

Official Source

Google is a Official Source. The source has been verified by Swipe Insight team.

Official Source
Google Analytics 4 Enhances Explore Filters with Expanded Match Types

Google Analytics 4 Enhances Explore Filters with Expanded Match Types

Tired of spending too much time creating audits for your clients?

Tired of spending too much time creating audits for your clients?

Featured
Google Analytics introduces Generated Insights feature for enhanced data analysis Trending ️‍πŸ”₯

Google Analytics introduces Generated Insights feature for enhanced data analysis

Google
Google

Official Source

Official Source

Google is a Official Source. The source has been verified by Swipe Insight team.

Official Source
BigQuery Data Transfer Service adds Google Analytics 4 reporting support Trending ️‍πŸ”₯

BigQuery Data Transfer Service adds Google Analytics 4 reporting support

Google Cloud
Google Cloud

Official Source

Official Source

Google Cloud is a Official Source. The source has been verified by Swipe Insight team.

Official Source
Google Analytics 4 Introduces Annotations and Anomaly Drivers Features Trending ️‍πŸ”₯

Google Analytics 4 Introduces Annotations and Anomaly Drivers Features

Josh Silverbauer
Josh Silverbauer

Top Creator

Top Analytics Creator

Josh Silverbauer is a Top Analytics Creator. Part of Swipe Insight Select, a curated list of top creators.

Top Analytics Creator
Google Analytics Introduces Percentage Values and Problem Detection Features

Google Analytics Introduces Percentage Values and Problem Detection Features

Google
Google

Official Source

Official Source

Google is a Official Source. The source has been verified by Swipe Insight team.

Official Source

Related Tools

Markifact logo

Markifact

Verified Tool

Verified Tool

Markifact is a Verified Tool. Want to get this badge? Contact us.

Verified Tool

Marketing Workflows Powered by AI

Featured
Marketing Auditor logo

Marketing Auditor

Verified Tool

Verified Tool

Marketing Auditor is a Verified Tool. Want to get this badge? Contact us.

Verified Tool

Automated audits for Google Ads and Analytics.

Get Featured Here

Showcase your tool in this list.

Contact Us
GA4 Auditor logo

GA4 Auditor

Verified Tool

Verified Tool

GA4 Auditor is a Verified Tool. Want to get this badge? Contact us.

Verified Tool

Automated GA4 audits with actionable insights

Data Analysis
Matomo logo

Matomo

Web analytics with full data ownership

Analytics
GA4 SQL logo

GA4 SQL

Verified Tool

Verified Tool

GA4 SQL is a Verified Tool. Want to get this badge? Contact us.

Verified Tool

Generate GA4 BigQuery queries easily

Data Analysis
PostHog logo

PostHog

All-in-one platform for product analytics and testing

Analytics
easyTag.io logo

easyTag.io

Effortless GA4 server-side tracking

Plausible Analytics logo

Plausible Analytics

Lightweight, privacy-friendly web analytics

Analytics
Akkio logo

Akkio

AI-powered analytics for agencies

Data Analysis
NinjaCat logo

NinjaCat

AI-powered marketing data and analytics platform

Reporting

Get Featured Here

Showcase your tool in this list.

Contact Us