WPForms Tracking with GTM, GA4 & Google Ads

WPForm is one of the popular WordPress form plugins that come with powerful features and flexibility. Recently, I have written WPForm’s tracking code for Google Tag Manager, which gives you form submission data and input values.

Furthermore, in the following tutorial, I have shared a step-by-step, in-depth guide to properly track WPForms with Google Tag Manager for Google Analytics 4 and Google Ads Enhanced Conversions.

WPForm Tracking Code for GTM

<script>
/**
* Author: Md Hasanuzzamna
* Linkedin: https://linkedin.com/in/md-h
* Youtube: https://youtube.com/@leomeasure
* Email: info@leomeasure.com
*/
(function() {
    // Ajax Form
    var ajaxForm = document.querySelectorAll('form.wpforms-ajax-form');
    if(ajaxForm.length) {
        var origXMLHttpRequest = XMLHttpRequest;
        XMLHttpRequest = function() {
            var requestURL;
            var requestMethod;
            var requestBody;

            var xhr = new origXMLHttpRequest();
            var origOpen = xhr.open;
            var origSend = xhr.send;

            xhr.open = function(method, url) {
                requestURL = url;
                requestMethod = method;
                return origOpen.apply(this, arguments);
            };

            xhr.send = function(data) {
                if (/.+\/admin-ajax\.php/.test(requestURL)) {
                    xhr.addEventListener('load', function() {
                        if (xhr.readyState === 4) {
                            if (xhr.status === 200) {
                                var response = JSON.parse(xhr.responseText);

                                if (response.success && (data instanceof FormData)) {
                                    requestBody = {};
                                    data.forEach(function(value, key) {
                                        if(key) {
                                            key = key.replace(/\[|\]/g, '_').replace(/_+/g, '_').replace(/^_|_$/g, '');
                                            requestBody[key] = value;
                                        }
                                    });

                                    if(requestBody.action === "wpforms_submit") {
                                        window.dataLayer = window.dataLayer || [];
                                        var wpFormData = Object.assign({}, requestBody);
                                        delete wpFormData['wpforms_nonce'];
                                        dataLayer.push({
                                            event: 'wpform_submit',
                                            formId: wpFormData['wpforms_id'],
                                            inputs: wpFormData
                                        });
                                    }
                                }
                            }
                        }
                    });
                }

                return origSend.apply(this, arguments);
            };

            return xhr;
        };
    }

    // Non Ajax Form
    var forms = document.querySelectorAll('form[id^="wpforms-form-"]:not(.wpforms-ajax-form)');
    forms.forEach(function(form) {
        var formId = form.getAttribute('data-formid');

        form.addEventListener('submit', function(event) {

            event.preventDefault();

            var form = this;
            var formData = new FormData(this);
            var wpFormData = {};

            var errorRequired = false;

             formData.forEach(function (value, key) {
                if(key) {
                    var inputField = form.querySelector('[name="'+key+'"]');

                    if(inputField) {
                        var fieldType = inputField.getAttribute('type');

                        var isRequiredField = inputField.classList.contains('wpforms-field-required');

                        if(isRequiredField) {
                            if(inputField.tagName === 'SELECT') {
                                var selectedOptionVal = inputField.options[inputField.selectedIndex].text;
                                if(!selectedOptionVal) {
                                    errorRequired = true;
                                }
                            } else if((inputField.getAttribute('type') === 'email') && (!value || !value.includes('@'))) {
                                 errorRequired = true;
                            }
                            else if(!value) {
                                errorRequired = true;
                            }
                        }
                    }

                    var formattedKey = key.replace(/\[|\]/g, '_').replace(/_+/g, '_').replace(/^_|_$/g, '');
                    wpFormData[formattedKey] = value;
                }
             });

             // required checkbox and radio button check 
             var requiredFieldSets = form.querySelectorAll('ul.wpforms-field-required');
             requiredFieldSets.forEach(function(fieldSet){
                if(fieldSet.querySelector('input[type="radio"]') || fieldSet.querySelector('input[type="checkbox"]')) {
                   if(!fieldSet.querySelector('input:checked')) {
                     errorRequired = true;
                   }
                }
             });   

            if(!errorRequired) {
                window.dataLayer = window.dataLayer || [];
                delete wpFormData['wpforms_nonce'];
                dataLayer.push({event: 'wpform_submit', formId: formId, inputs: wpFormData});
            }

        });
    });
})();
</script>

How to check it is wpforms or not?

open the form page and inspect

FIrst, create a new tag

For triggering

ANd save it

send information to GA4

Create a new variable first

FOr triggering

Now, Create a new tag

Trigger

Preview it again

After submitting the form again, let’s preview and see what’s happening in GTM

So, everything is okay.Now submit it and publish.

This is the process to send information to google analytics

Conversion tracking for Google ad conversion

create a new variable first

we will use this variable for email tracking purpose

variable for phone number

Now, we will create another variable for phone number. So, without starting from scratch, we will copy this email variable first for speed up the process

we will just rename it and change the phone number field after the inputs.

the phone number is in the wpforms.fields.5 , so we will replace it.

Then save it

Now, go to google tag manager

create a new tag

For Triggering

Now, we need conversion linker. Here is the simple process to do that.

Again, preview it

3 thoughts on “WPForms Tracking with GTM, GA4 & Google Ads”

Leave a Comment

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

Get A Quote

Please contact us for expert guidance & personalized solutions to maximizing the potential of Google Analytics for your business.

Send Us A Message

    Contact Us

    Please contact us for expert guidance & personalized solutions to maximizing the potential of Google Analytics for your business.

    Send Us A Message