This JavaScript code enhances the default behavior of Contact Form 7’s form submission event. It listens for the form submission event, processes the form data, and pushes it to the Google Tag Manager data layer as a structured object. This allows for easier tracking and analysis of form submissions.
Add the Script: Copy the following code and add it to your website’s script file or directly into the HTML.
<script>
document.addEventListener('wpcf7mailsent', function(event) {
var responseArray = event.detail.inputs;
var formattedResponse = {};
responseArray.forEach(function(input) {
formattedResponse[input.name] = input.value;
});
window.dataLayer.push({
"event": "cf7submission",
"formId": event.detail.contactFormId,
"response": formattedResponse
});
});
</script>
Configure Google Tag Manager: Ensure that you have Google Tag Manager set up on your website. The script will push the form submission data to the data layer, where it can be used to trigger tags or track form submissions.
Create Triggers and Tags: In Google Tag Manager, create triggers and tags based on the cf7submission
event and the structured data provided by the script.
wpcf7mailsent
event, which is fired when a Contact Form 7 form is successfully submitted.dataLayer
, where it can be accessed by Google Tag Manager for further processing.If a form is submitted with the following fields:
The data pushed to the dataLayer
will look like this:
{
"event": "cf7submission",
"formId": "1234",
"response": {
"your-name": "John Doe",
"your-email": "john.doe@example.com",
"your-message": "Hello!"
}
}
This project is licensed under the MIT License. See the LICENSE file for details.
Feel free to submit issues or pull requests if you have any improvements or bug fixes.