MeasureSchool logo
Search
Close this search box.
Search
Close this search box.

How to Capture UTM Parameters in a Cookie and Transfer Them to a (Hidden) Form Field

Last Modified on March 25, 2024

Do you want to know where your website visitors are coming from? Are they coming from a paid source or an unpaid source?

GTM For Beginners

Sign up to the FREE GTM for Beginners Course...

We can capture this source information in a cookie using UTM parameters and hidden form fields!

Having source data for users provides a more holistic view of our tracking data. You can use this information to increase your online presence where your visitors are active and interested.

In this guide, I’ll show you how you can take your UTM source parameters from your landing page and transfer them into a hidden form field. 

Here’s an overview of what we’ll cover in this guide:

 

So let’s dive in.

Why Capture UTM Parameters in Hidden Form Fields Using a Cookie?

The source information for a website visitor is oftentimes available in an analytics tool like Google Analytics. But this information can be even more useful if we also have it in our CRM system. 

However, if you want the information also in your Google Analytics, check out our guide to learn how to track UTM codes in GA4.

This way, we can learn where users who engage with our site (say, by submitting a form or signing up for a newsletter) came from.

However, there is a small problem to this. The source information is available to us only on the landing page.

Once the user navigates to a new page, we as marketers will lose this information.

The solution to this problem is to attach the source information to the user by carrying it over in a form field. But then there’s the issue of user experience and clogging their view with tracking data.

So how could you fill these UTM parameters in a hidden form field?

This is where a cookie comes in. With a cookie, we can store the source information. Once the user is ready to submit the form, we can take that information from the cookie and use it to populate a form field. 

And since we’ll be using a hidden form field, it won’t mess with the user experience. It’s a win-win!

So let’s start by creating a form field!

Creating a Form Field to Capture the Contact Information

We’ll use the popular Contact Form 7 on our demo shop website as an example. (This demo site already has Google Tag Manager installed. But if you haven’t done this already, check out this handy guide to install Google Tag Manager!)

The website visitor fills out their information in Contact Form 7

Contact Form 7 on the demo shop web page

But to store our source information, we’ll create another hidden form field that will capture our UTM parameters.

You can do this by going into your WordPress site backend and adding another field to the Contact Form 7. This won’t be a hidden field yet, but we’ll get to that in a minute.

Adding a form field to capture UTM parameters in the WordPress settings of the demo shop web page

Next, we want to collect the UTM parameters using Google Tag Manager.

Getting UTM Data in Google Tag Manager

Let’s first go into our Google Tag Manager account and create a new Tag. 

We’ll use a custom Tag template called the Persist Campaign Data which stores URL parameters in a browser cookie.

Importing Tag template Persist Campaign Data to capture UTM parameters in Google Tag Manager

Next, we’ll want to configure this Tag to Store campaign data in a browser cookie. So let’s check this option. 

The second option is to Push original location into dataLayer. But we’ll leave it unchecked for now.

Check the option to Store campaign data in a browser cookie and uncheck the option to Push origins location in dataLayer

Then we’ll enter the UTM parameters that we want to store such as the utm_source, utm_medium, utm_content, utm_campaign, etc. Make sure to separate each parameter with a comma.

Note: Avoid adding parameters with user information as it might violate privacy laws. You could put in the Facebook ID as a parameter but Facebook doesn’t allow you to connect the data just yet. So, adding the Facebook ID at this point won’t make any difference.

This data will be written to the Campaign URL cookie

We also have a Referrer cookie that stores the referrer when there are no UTM parameters filled out. 

Configuring the Persist Campaign Data Tag to store UTM parameters in Google Tag Manager

Lastly, we’ll attach a trigger to this Tag. 

Since we don’t know which page the user uses to enter our website, we’ll fire the Tag on all pages. So let’s attach an All Pages trigger.

Go ahead and Save the Tag. 

Our Tag is now ready! We can check the Tag in the preview mode. And if it is configured correctly, it should fire on our page and store the information in a cookie.

Persist Campaign Data Tag fires on our demo shop web page

You might be interested in viewing this cookie. So let’s take a look!

How to View Cookies

Go to More Tools → Developer Tools under the Chrome menu and under the Application tab you’ll find the Cookies. 

This is where our Campaign URL cookie, __gtm_campaign_url, will be stored.

Cookies stored in our demo shop website

It will give us the entire URL from where the user came. This URL will be in encoded form. And we’ll need to decode it for our use. We’ll see how to do this later on.

For now, we want to make this value available in Google Tag Manager. We can do that using a cookie variable.

Let’s see how!

Creating a Cookie Variable in Google Tag Manager

First, we’ll create a new user-defined variable of the type 1st Party Cookie. We’ll then enter the name of the cookie that we had created.

The next option is URI-decode cookie. This option decodes our encoded URL. So we’ll keep it checked.

Configuring the cookie variable to capture UTM parameters in Google Tag Manager

Next, we’ll give the variable a name and click on the Save button. 

Our variable is now configured and it will be able to read our cookie. We should see a decoded URL under the Message tab of the Variables menu in the GTM debug console.

Source URL decoded and stored in a cookie variable in Google Tag Manager

This means we now have the information that was passed through UTM parameters available to us.

You might wonder if we really need to store this information in a cookie.

This cookie is important because the UTM parameters disappear the moment we navigate from our landing page. These parameters are available only on the landing page of our session. 

And so, we wouldn’t be able to fetch them using a URL variable. But with a cookie, we can store them and use them at any later stage even if they are not available in the URL anymore.

Next, we’ll write this cookie data into the form field that we had created.

Filling the Form Field with Cookie Data

This step is actually quite easy!

All we need to do is use a JavaScript code and add it to a custom HTML Tag. To make things easier for you, I’ve already prepared a script.

We’ll copy the code from the script and paste it into our custom HTML Tag.

<script>
(function () {
var value = ""         //fill with variable which information should be written into the field
var selector = ""      //fill with CSS Selector that identifies the form field
var field = document.querySelector(selector)
if(field){ field.value = value; }
})();
</script>

And then add the cookie variable name and CSS Selector in the code.

Top Tip: To find the CSS Selector, right-click the HTML element and go to Inspect. 

Creating a Custom HTML Tag in Google Tag Manager to fill the form with UTM parameters stored in a cookie

The last step of our Tag configuration is to attach a trigger to this Tag. The trigger, in this case, will be dependent on where the form field is located.

So we will select the Page View – DOM Ready trigger. We choose the DOM Ready event because we want to make sure that our form field actually exists when the document object model is loaded.

That’s it!

Click on the Save button and our Tag is ready.

Attaching the Page View - DOM Ready trigger to our Tag in Google Tag Manager

If you reload the Contact Form 7 page, it will fire our Tag and fill the form field with the URL.

And if the user submits the form, it will send all the data along with the source URL to your mail.

Data from the Contact Form 7 sent to your mail

Hiding the Form Field

The URL information in the form field is actually auto-filled. So we don’t really need the form field to be visible to the user.

In fact, such extra elements on the web page can also interfere with the user experience. So we’ll keep it hidden from the user.

To hide the form field, go to Contact Form 7 and add hidden before the form field name in the form template editor. 

Hiding the form field that captures UTM parameters from Contact Form 7

Hiding the form field from Contact Form 7

Even after hiding it, the form field will still be available in the background. You can access it any time using the Inspect option of the web page.

Hidden input field of Contact Form 7

However, what happens if there’s no UTM source or there are no UTM parameters when the user comes to the page? In this case, you can use the referrer cookie. 

Using the referrer cookie isn’t always very simple or user-friendly. It usually requires some fiddling with the trigger and a dynamic filling out of either the UTM parameters or the referrals. This will depend on your implementation, so you may need to troubleshoot this independently.

Finally, just click on the Submit button to make these changes live on your website. 

Summary

All right, so there you have it. This is how you can capture your UTM parameters using form fields from the landing page.

This technique can be broadened and used at a more advanced level by setting up multiple hidden form fields. You could also have different information, like the multiple sources from where the user came.

So if the user came first from Facebook, then from Google Ads, and then from a referrer, you could fill this all into a hidden form field. 

What if I can’t do this myself? We have had a few people who said this is too hard as I don’t have the technical capabilities. If you are in that boat, a few companies can do it for you. One such company with a tool that does it for you is attributer.io which I found from a quick Google search. They help you get marketing channel attribution data into your CRM.

We also have a guide on tracking initial traffic sources using a cookie for the multi-source approach. But the basic technique would still stay the same. We take the source information, put it into a cookie, then fill it out later on into our hidden form fields.

So how do you track the source of your website visitors? Have you ever used a cookie to store this information? Let us know all about it in the comments below!

FAQ

How can I get UTM data in Google Tag Manager?

To get UTM data in Google Tag Manager, you can use a custom Tag template called "Persist Campaign Data." This Tag stores the UTM parameters in a browser cookie. Configure the Tag to store the desired UTM parameters and attach it to a trigger that fires on all pages.

How can I create a form field to capture UTM parameters?

To create a form field for capturing UTM parameters, you can use a form plugin like Contact Form 7 in WordPress. Add a new field to your form and specify it as a hidden field. This field will capture the UTM parameters without interfering with the user experience.

How do I fill the form field with cookie data in Google Tag Manager?

To fill the form field with cookie data, you can use a JavaScript code snippet in a custom HTML Tag. The code retrieves the UTM parameters stored in the cookie and assigns them to the hidden form field. This ensures that the UTM parameters are automatically populated in the form when a user submits it.

MeasureMasters

REOPENED!

Master Data & Analytics with MeasureMasters

Exclusive Courses & Workshops | Ongoing Troubleshooting | Support Resources, Tools & much more
Subscribe
Notify of
guest
40 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Jhun Agustin
Jhun Agustin
3 years ago

Hi Julian, I’ve been looking for this kind of article since like 1 month ago. It is exactly what I am looking for a project I am working on. I have a question though, have you also tried doing this on a third party form being embeded on your own site? Let say, I have an iframed 123Forms on my site with hidden fields too.

Pieter Leeflang
Pieter Leeflang
3 years ago

Would you have an example of how the form fill code would be if there were multiple variables and multiple hidden fields?

Angeliki
Angeliki
3 years ago

Hello Julian,

How can we distinguish utm_source, utm_medium etc. and get their values in different from fields?
Thank you

Cedric
Cedric
3 years ago

I managed to save the cookie but its all in 1 hidden field.

Cedric
Cedric
3 years ago
Reply to  Angeliki

Hi, Have you found a solution to this one?

Nechama
Nechama
3 years ago

Do you have any more information about the multi-source approach?

Max
Max
3 years ago

Hi Julian,
Thank you for this solution for capturing utm parameters. It’s very helpful. I have a question about the result I’m getting for the source value. Rather than the URL with utm parameters, the value is a sendgrid URL. I can see that the cookie captures the UTL with utm parameters okay, so I don’t think it’s the cookie. To confirm, it’s a Contact Form 7. Do you have any ideas or suggestions?
Thank you 🙂

Last edited 3 years ago by Max
Daniel
Daniel
3 years ago

Hi Julia,.
any idea why I keep getting an error message when trying to preview/publish with the following message:

Unknown variable “cookie – __gtm_campaign_url” found in a tag. Edit the tag and remove the reference to the unknown variable.

I followed your setup to the T, it is all exactly the same, yet this error keeps coming.

Many thanks.

Last edited 3 years ago by Daniel
Daniel
Daniel
3 years ago

Hi Julian, I have done exactly that. All seems to be set up correctly, actually, it is exactly as in your video tutorial. Yet, it won’t save, keep telling me that the variable is unknown.

Last edited 3 years ago by Daniel
Cedric
Cedric
3 years ago
Reply to  Daniel

The variable name must be the same as the one you set in the HTML code

Cedric
Cedric
3 years ago

Hey Julian,
Since we are moving towards a cookie-less experience. How would this hold up when it happens?

Cedric
Cedric
3 years ago

Will you make a tutorial about this in the future? or at least an overview of solutions?

Anna Taylor
Anna Taylor
3 years ago

Hi Julian,

This is so helpful as a someone with a vague understanding of code who needs to track.

Like others here, I have created a single cookie and I need to parse UTM values into separate fields. I have found some sample code for how to use a query selector to do this, but it is designed to parse data from separate cookies into fields.

To fill separate form fields, do I need separate cookies?

Thanks!

Cedric
Cedric
2 years ago

Ah, the solution is in the javascript code example that you gave.

Marjan
Marjan
3 years ago

Hi Julian! Thank you so much for this explanation! 🙂 I was wondering if storing this data is GDPR-proof? Does the new iOs-14 update have an impact on this?
Thanks again!

Rob
Rob
2 years ago

Hi Julian, great work, as usual, i did have a quick question on the cookie lifespan i believe it’s per session and not a 30-day window etc? and also I though I share this script for all the people using elementor were you can’t set the “name” without it appearing with additional names. keep up the good work!!! <script>  var queryForm = function(settings) {   var reset = settings && settings.reset ? settings.reset : false;   var self = {{Var Cookie __gtm_campaign_url}}   var querystring = self.split(“?”);  if (querystring.length > 1) {   var pairs = querystring[1].split(“&”);   for (i in pairs) {    var keyval… Read more »

Marc Roth
Marc Roth
1 year ago

Hey Julian, would I need to create that for every form that I host on my website? Meaning: I am a lead gen agency and we have hundreds of forms. Each and every form is different. Well… the hidden field might always be the same (we´re using active campaign). Still – would I need to do this over and over again for every form or will this logic be applied to all forms that contain the hidden field that i want to be filled?

Peter
Peter
1 year ago

Hi Julian,

thx for the great article. unfortunately I failed in one of the last steps since I am not a programmer. It appears like I am doing something wrong with the selector line

any idea?

<script>
(function () {
var value = "{{gtm-campagin}}"        
var selector = "input[name="source"]"      
var field = document.querySelector(selector)
if(field){ field.value = value; }
})();
</script>

I also tried it with  "input[name='source']" but still get errors. the CF7 field says "undefined"
Last edited 1 year ago by Peter
Pradeep
Pradeep
1 year ago
Reply to  Peter

Hi Julian,
We use wix forms on our website. Is it possible to pass the UTM data following the same process? I think I might need to change the javascript code. Can you help me with this?

Avi Kleiman
Avi Kleiman
1 year ago

Hi Julian,

Great vid, but I reached a problem. in my console there is no data and when I type in the document.querySelector e.t.c. it comes up with null. What do I do?

Second question. Will this work in Gravity Forms?

Thank you for your help,

All the best,

Avi

lisa
lisa
1 year ago

Need some help for gravity forms in finding the exact input.

Gabriel
Gabriel
1 year ago

How would I use this method to write UTM parameters to a pop up form? Thank you!

Sheldon Casper
Sheldon Casper
1 year ago

Hey Julian, Great tutorial!

I have the standard implementation as you’ve instructed working perfectly…

However, I am passing this data to my CRM and I only need the value of the utm_term parameter.

How can I edit the JS you’ve provided to just assign the utm_term value to my designated form field instead of sending the entire URL?

Thank you for you assistance!

Willy
Willy
1 year ago
Reply to  Sheldon Casper

The best way to do this is setting up User-Defined Variables in GTM with type URL, component Query and query key ‘utm_term’ . Use this variable in the custom HTML (this line –> var value = “”     //fill with variable which information should be written into the field).

This works also for separating the source, campaign and campaign.

Bored Dev
Bored Dev
1 year ago

Hi. Is it possible to change the expire time ?

Hagen
Hagen
11 months ago

Hi Julian, I tried this method on our wix site, but it doesn´t work. I assume it´s because the form is in a lightbox. Do you have a tip for me how to do it in wix?

jackson
jackson
4 months ago

Hey Julian, great article. Thank you for taking the time to put it together. Is this method still in compliance by todays standards? Also how long will the cookie track for? 30 days or is it by session? Thank you!

sha
sha
4 months ago

Hi Julian,

Thanks for the amazing tutorial, i have followed all the steps but i am getting below error:

Unknown variable “cookie – __gtm_campaign_url” found in a tag. Edit the tag and remove the reference to the unknown variable.


MeasureSchool Locker

Unlock our Free Tools, Templates and Resources

now it's time to

Start measuring like a master

Itching to jump into the world of MeasureMasters? This is what you have to look forward to.

Ready to take your digital marketing to the next level?

Subscribe to our newsletter and stay ahead with our latest tips and strategies.