Capture UTM parameters in Elementor Forms Using Cookies

Views: 146

In this quick guide, I will demonstrate how to keep UTM parameters in cookies and collect this information in Elementor Forms without losing it when a visitor changes pages. Many articles on the Internet propose solutions for when a user has UTM parameters in the URL, but this solution is more flexible.

In the video, you can see how I do it in practice.

We need to complete two steps:

  1. Add specific code to “Elementor” -> “Custom Code”.
  2. Add hidden fields to an Elementor Form.

Step 1:

  1. Log in as an admin to your website.
  2. Choose “Elementor” -> “Custom Code”.
  3. Click “Add New”.
  4. Paste the code below:
<script>
	// We are waiting for the full page to load before loading this feature. This prevents a few bugs.
	window.addEventListener('load', function () {
		var queryForm = function(settings) {
			// Parsing URL
			var reset = settings && settings.reset ? settings.reset : false;
			var self = window.location.toString();
			var querystring = self.split("?");

			// Checking for parameters in the URL
			if (querystring.length > 1) {
				var pairs = querystring[1].split("&");
				// Iterating through all key-value pairs
				for (i in pairs) {
					var keyval = pairs[i].split("=");
					// Condition to only save "utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content" in cookies
					if (reset || sessionStorage.getItem(keyval[0]) === null) {
						if (["utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content"].includes(keyval[0])) {
							const d = new Date();
							// Setting cookie expiration time to 14 days
							d.setTime(d.getTime() + (14 * 24 * 60 * 60 * 1000));
							let expires = "expires=" + d.toUTCString();
							// Setting the cookie
							document.cookie = keyval[0] + "=" + keyval[1] + ";" + expires + ";path=/";
						}
					}
				}
			}

			// Function to get the value of a cookie by its name
			function getCookie(cname) {
				let name = cname + "=";
				let ca = document.cookie.split(';');
				for(let i = 0; i < ca.length; i++) {
					let c = ca[i];
					while (c.charAt(0) == ' ') {
						c = c.substring(1);
					}
					if (c.indexOf(name) == 0) {
						return c.substring(name.length, c.length);
					}
				}
				return "";
			}
				
			// Finding all hidden fields and text input fields in the form
			var hiddenFields = document.querySelectorAll("input[type=hidden], input[type=text]");

			// Iterating through all found fields
			for (var i=0; i < hiddenFields.length; i++) {

				var elementor_field_name = hiddenFields[i].name;
				var elementor_field_name_clean = elementor_field_name.match(/\[(.*?)\]/);

				if(elementor_field_name_clean) {
					// Getting the cookie value for the corresponding parameter
					var param = getCookie(elementor_field_name_clean[1]);
				}

				// If a corresponding parameter is found in the cookies, populate the field
				if(param) {
					 document.getElementsByName(hiddenFields[i].name)[0].value = param;
				}
			}
		}
		setTimeout(function() {
			queryForm();
		}, 3000);
	})
</script>

For MetForm use following Code,

Replace this section:

"var elementor_field_name_clean = elementor_field_name.match(/\[(.*?)\]/);
if(elementor_field_name_clean) {
    var param = getCookie(elementor_field_name_clean[1]);
}"

With this:

"var elementor_field_name_clean = elementor_field_name.match(/\[(.*?)\]/);
if(elementor_field_name_clean) {
    var param = getCookie(elementor_field_name_clean[1]);
} else if (["utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content"].includes(elementor_field_name)) {
    var param = getCookie(elementor_field_name);
}"

so the final code will be like this,

<script>
	// We are waiting for the full page to load before loading this feature. This prevents a few bugs.
	window.addEventListener('load', function () {
		var queryForm = function(settings) {
			// Parsing URL
			var reset = settings && settings.reset ? settings.reset : false;
			var self = window.location.toString();
			var querystring = self.split("?");

			// Checking for parameters in the URL
			if (querystring.length > 1) {
				var pairs = querystring[1].split("&");
				// Iterating through all key-value pairs
				for (i in pairs) {
					var keyval = pairs[i].split("=");
					// Condition to only save "utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content" in cookies
					if (reset || sessionStorage.getItem(keyval[0]) === null) {
						if (["utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content"].includes(keyval[0])) {
							const d = new Date();
							// Setting cookie expiration time to 14 days
							d.setTime(d.getTime() + (14 * 24 * 60 * 60 * 1000));
							let expires = "expires=" + d.toUTCString();
							// Setting the cookie
							document.cookie = keyval[0] + "=" + keyval[1] + ";" + expires + ";path=/";
						}
					}
				}
			}

			// Function to get the value of a cookie by its name
			function getCookie(cname) {
				let name = cname + "=";
				let ca = document.cookie.split(';');
				for(let i = 0; i < ca.length; i++) {
					let c = ca[i];
					while (c.charAt(0) == ' ') {
						c = c.substring(1);
					}
					if (c.indexOf(name) == 0) {
						return c.substring(name.length, c.length);
					}
				}
				return "";
			}
				
			// Finding all hidden fields and text input fields in the form
			var hiddenFields = document.querySelectorAll("input[type=hidden], input[type=text]");

			// Iterating through all found fields
			for (var i=0; i < hiddenFields.length; i++) {

				var elementor_field_name = hiddenFields[i].name;
				var elementor_field_name_clean = elementor_field_name.match(/\[(.*?)\]/);
				if(elementor_field_name_clean) {
    		var param = getCookie(elementor_field_name_clean[1]);
				} else if (["utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content"].includes(elementor_field_name)) {
    		var param = getCookie(elementor_field_name);
			}

				// If a corresponding parameter is found in the cookies, populate the field
				if(param) {
					 document.getElementsByName(hiddenFields[i].name)[0].value = param;
				}
			}
		}
		setTimeout(function() {
			queryForm();
		}, 3000);
	})
</script>

This handles both Elementor Forms and metForm name structures. Just make sure your metForm fields are named exactly: utm_source, utm_medium, etc.

For MetForm Separate Form the code will be,

<script>
window.addEventListener('load', function () {
    // URL parsing (this stays the same for all forms)
    var self = window.location.toString();
    var querystring = self.split("?");
    
    if (querystring.length > 1) {
        var pairs = querystring[1].split("&");
        for (i in pairs) {
            var keyval = pairs[i].split("=");
            if (["utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content"].includes(keyval[0])) {
                const d = new Date();
                d.setTime(d.getTime() + (14 * 24 * 60 * 60 * 1000));
                let expires = "expires=" + d.toUTCString();
                document.cookie = keyval[0] + "=" + keyval[1] + ";" + expires + ";path=/";
            }
        }
    }

    function getCookie(cname) {
        let name = cname + "=";
        let ca = document.cookie.split(';');
        for(let i = 0; i < ca.length; i++) {
            let c = ca[i];
            while (c.charAt(0) == ' ') {
                c = c.substring(1);
            }
            if (c.indexOf(name) == 0) {
                return c.substring(name.length, c.length);
            }
        }
        return "";
    }

    setTimeout(function() {
        // For Form 1
        if (document.querySelector('#form1')) {
            var form1Fields = document.querySelectorAll("#form1 input[type=hidden], #form1 input[type=text]");
            for (var i=0; i < form1Fields.length; i++) {
                var elementor_field_name = form1Fields[i].name;
                var elementor_field_name_clean = elementor_field_name.match(/\[(.*?)\]/);
                if(elementor_field_name_clean) {
                    var param = getCookie(elementor_field_name_clean[1]);
                } else if (["utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content"].includes(elementor_field_name)) {
                    var param = getCookie(elementor_field_name);
                }
                if(param) {
                    form1Fields[i].value = param;
                }
            }
        }
        
        // Repeat similar blocks for form2, form3...
    }, 3000);
})"
</script>

Step 2:

  1. Open your Elementor form fields and add a new hidden field. For the Label, enter utm_source.
  2. Go to the Advanced tab, then in the Default Value field, click the Dynamic Tags icon. Select Request Parameter and set the Key to utm_source.
UTM Source Content
  1. Duplicate this process for the other fields:
    • utm_medium
    • utm_campaign
    • utm_term
    • utm_content
List of UTM parameters form fields

You should end up with five hidden fields:

  • utm_source
  • utm_medium
  • utm_campaign
  • utm_term
  • utm_content

DONE! This is the easiest way to collect this information.

Now that your UTMs are stored in Elementor, you can generate reports on campaign performance, transfer data to your CRM, and more.

Source : reshetar.dev

Author: