Wordpress, GoHighLevel

How to track UTM’s in WordPress and into your GoHighLevel Embedded Form

Share :

Table of Contents

So you’re running ads to your WordPress website, you’ve got a GoHighLevel form embedded on your page, and you want to know where your leads are actually coming from. Facebook? Google? YouTube? Makes sense—you’re spending money on advertising, and you need to know what’s working.

Here’s the problem though.

Someone clicks your ad, lands on your homepage with all those beautiful UTM parameters in the URL, and then… they don’t fill out the form right away. They go check out your pricing page. They read your About Us. They browse around a bit. And when they finally come back to fill out that form?

Your UTMs are gone. Poof. Lost forever.

Now you’ve got a lead and no idea where they came from. Not great.

Let me show you how to fix this with two simple scripts—one for WordPress and one for your GoHighLevel form.

The Problem: UTMs Don’t Stick Around

Here’s what normally happens:

1. Someone clicks your ad with a URL like yoursite.com?utm_source=facebook&utm_campaign=summer_sale
2. They land on your page—UTMs are in the URL
3. They click to another page on your site
4. UTMs are gone from the URL
5. They fill out your form
6. You have no idea where they came from

Your GoHighLevel form can only grab UTM parameters if they’re actually in the URL when the form loads. Once your visitor navigates to a different page, those parameters disappear.

The Solution: Cookie Those UTMs

What we need to do is:

1. Grab the UTMs when someone first lands on your site
2. Store them in a cookie so they persist across pages
3. Pass them to your GHL form when it loads

This takes two scripts—one on your WordPress site and one on your GoHighLevel form. Let me walk you through both.

Step 1: Add the WordPress Script

This script goes in your WordPress theme’s functions.php file. It captures UTM parameters from the URL and stores them in cookies. Then, when someone navigates around your site, those UTMs stick with them.

To add it:

1. Go to Appearance → Theme File Editor in your WordPress admin
2. Select functions.php from the right sidebar
3. Scroll to the bottom of the file
4. Paste this entire code block:

				
					// Add UTM tracking script to WordPress
function add_utm_tracking_script() {
    ?>
    <script>
    (function() {
        'use strict';

        var CONFIG = {
            cookieExpireDays: 30,
            cookiePrefix: 'utm_',
            storageKey: 'utm_params',
            utmParams: [
                'utm_source',
                'utm_medium',
                'utm_campaign',
                'utm_term',
                'utm_content',
                'utm_id',
                'gclid',
                'fbclid'
            ]
        };

        var CookieUtil = {
            set: function(name, value, days) {
                var expires = '';
                if (days) {
                    var date = new Date();
                    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                    expires = '; expires=' + date.toUTCString();
                }
                document.cookie = name + '=' + encodeURIComponent(value) + expires + '; path=/; SameSite=Lax';
            },
            get: function(name) {
                var nameEQ = name + '=';
                var cookies = document.cookie.split(';');
                for (var i = 0; i < cookies.length; i++) {
                    var cookie = cookies[i].trim();
                    if (cookie.indexOf(nameEQ) === 0) {
                        return decodeURIComponent(cookie.substring(nameEQ.length));
                    }
                }
                return null;
            }
        };

        var StorageUtil = {
            set: function(key, data) {
                try {
                    localStorage.setItem(key, JSON.stringify(data));
                } catch (e) {}
            },
            get: function(key) {
                try {
                    var data = localStorage.getItem(key);
                    return data ? JSON.parse(data) : null;
                } catch (e) {
                    return null;
                }
            }
        };

        var UTMTracker = {
            processedIframes: new WeakSet(),

            getUTMsFromURL: function() {
                var params = new URLSearchParams(window.location.search);
                var utms = {};
                CONFIG.utmParams.forEach(function(param) {
                    var value = params.get(param);
                    if (value) {
                        utms[param] = value;
                    }
                });
                return utms;
            },

            getStoredUTMs: function() {
                var utms = {};
                CONFIG.utmParams.forEach(function(param) {
                    var value = CookieUtil.get(CONFIG.cookiePrefix + param);
                    if (value) {
                        utms[param] = value;
                    }
                });
                if (Object.keys(utms).length === 0) {
                    var stored = StorageUtil.get(CONFIG.storageKey);
                    if (stored) {
                        return stored;
                    }
                }
                return utms;
            },

            storeUTMs: function(utms) {
                if (Object.keys(utms).length === 0) return;
                Object.keys(utms).forEach(function(param) {
                    CookieUtil.set(CONFIG.cookiePrefix + param, utms[param], CONFIG.cookieExpireDays);
                });
                var existingUTMs = this.getStoredUTMs();
                var mergedUTMs = Object.assign({}, existingUTMs, utms);
                StorageUtil.set(CONFIG.storageKey, mergedUTMs);
            },

            getAllUTMs: function() {
                var storedUTMs = this.getStoredUTMs();
                var urlUTMs = this.getUTMsFromURL();
                return Object.assign({}, storedUTMs, urlUTMs);
            },

            updateIframes: function() {
                var self = this;
                var utms = this.getAllUTMs();
                if (Object.keys(utms).length === 0) {
                    return;
                }

                var iframes = document.querySelectorAll('iframe');

                iframes.forEach(function(iframe) {
                    if (self.processedIframes.has(iframe)) {
                        return;
                    }

                    var src = iframe.getAttribute('src');
                    if (!src) return;

                    if (src.indexOf('youtube') !== -1 || 
                        src.indexOf('vimeo') !== -1 || 
                        src.indexOf('wistia') !== -1 ||
                        src.indexOf('vidyard') !== -1) {
                        self.processedIframes.add(iframe);
                        return;
                    }

                    try {
                        var url = new URL(src, window.location.origin);
                        var modified = false;

                        Object.keys(utms).forEach(function(param) {
                            if (!url.searchParams.has(param)) {
                                url.searchParams.set(param, utms[param]);
                                modified = true;
                            }
                        });

                        self.processedIframes.add(iframe);

                        if (modified) {
                            iframe.setAttribute('src', url.toString());
                        }
                    } catch (e) {
                        self.processedIframes.add(iframe);
                    }
                });
            },

            init: function() {
                var self = this;

                var urlUTMs = this.getUTMsFromURL();
                if (Object.keys(urlUTMs).length > 0) {
                    this.storeUTMs(urlUTMs);
                }

                if (document.readyState === 'loading') {
                    document.addEventListener('DOMContentLoaded', function() {
                        self.updateIframes();
                    });
                } else {
                    self.updateIframes();
                }

                window.addEventListener('load', function() {
                    setTimeout(function() {
                        self.updateIframes();
                    }, 500);
                });

                var observer = new MutationObserver(function(mutations) {
                    var hasNewIframes = false;
                    mutations.forEach(function(mutation) {
                        mutation.addedNodes.forEach(function(node) {
                            if (node.nodeName === 'IFRAME') {
                                hasNewIframes = true;
                            } else if (node.querySelectorAll) {
                                var iframes = node.querySelectorAll('iframe');
                                if (iframes.length > 0) {
                                    hasNewIframes = true;
                                }
                            }
                        });
                    });
                    if (hasNewIframes) {
                        self.updateIframes();
                    }
                });

                if (document.body) {
                    observer.observe(document.body, { childList: true, subtree: true });
                } else {
                    document.addEventListener('DOMContentLoaded', function() {
                        observer.observe(document.body, { childList: true, subtree: true });
                    });
                }

                window.UTMData = this.getAllUTMs();
            }
        };

        window.UTMTracker = {
            getUTMs: function() { return UTMTracker.getAllUTMs(); },
            getUTM: function(param) { var utms = UTMTracker.getAllUTMs(); return utms[param] || null; }
        };

        UTMTracker.init();
    })();
    </script>
    <?php
}
add_action('wp_head', 'add_utm_tracking_script', 1);
				
			
5. Click Update File

Important: If you’re using a theme that gets updated regularly, use a child theme so you don’t lose this code when the theme updates.

Step 2: Add the GoHighLevel Form Script

Here’s the thing—your GHL form loads in an iframe. Because of browser security, the WordPress script can’t reach inside that iframe to populate the fields directly. So we need a second script that lives on the form itself.

This script pulls the UTM parameters from the URL (which WordPress passes to the iframe) and populates your form fields.

To add it:

1. Edit your form in GoHighLevel
2. Look for Code widget and drag it somewhere onto your form
3. Click the Edit Code blue button on the right side where the edit slideout appears.
4. Paste this script into the pop up window:

				
					<script>
(function() {
    function getUTMParams() {
        var params = new URLSearchParams(window.location.search);
        return {
            utm_source: params.get('utm_source') || '',
            utm_medium: params.get('utm_medium') || '',
            utm_campaign: params.get('utm_campaign') || '',
            utm_term: params.get('utm_term') || '',
            utm_content: params.get('utm_content') || '',
            utm_id: params.get('utm_id') || '',
            gclid: params.get('gclid') || '',
            fbclid: params.get('fbclid') || ''
        };
    }

    function populateFields() {
        var utms = getUTMParams();

        Object.keys(utms).forEach(function(param) {
            if (utms[param]) {
                var selectors = [
                    'input[name="' + param + '"]',
                    'input[name*="' + param + '"]',
                    'input[id="' + param + '"]',
                    'input[id*="' + param + '"]',
                    'input[placeholder*="' + param + '"]',
                    'textarea[name="' + param + '"]',
                    'textarea[name*="' + param + '"]'
                ];

                selectors.forEach(function(selector) {
                    var fields = document.querySelectorAll(selector);
                    fields.forEach(function(field) {
                        field.value = utms[param];
                    });
                });
            }
        });
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', populateFields);
    } else {
        populateFields();
    }

    setTimeout(populateFields, 500);
    setTimeout(populateFields, 1000);
    setTimeout(populateFields, 2000);
})();
</script>
				
			
4. Save your form

Step 3: Add UTM Fields to Your Form

Make sure your GoHighLevel form actually has fields to capture the UTMs. Add these fields to your form:

  • utm_source – Hidden (or visible for testing)
  • utm_medium – Hidden
  • utm_campaign – Hidden
  • utm_term – Hidden
  • utm_content – Hidden
  • utm_id – Hidden
  • gclid – Hidden
  • fbclid – Hidden

You don’t need all of them—just add the ones you’re actually using in your advertising. The standard ones are utm_source, utm_medium, and utm_campaign.

Pro tip: When you’re testing, make these fields visible so you can actually see the values populate. Once you confirm it’s working, switch them to hidden fields.

How It All Works Together

Let me break down what happens when someone clicks your ad:

1. They land on your site with UTMs in the URL
2. WordPress script grabs those UTMs and stores them in cookies (good for 30 days)
3. They browse around your site—pricing, about us, wherever
4. UTMs stay in the cookies the whole time
5. They come back to a page with your form
6. WordPress script adds the UTMs to the iframe URL
7. GHL script reads the URL and populates the form fields
8. They submit the form and you know exactly where they came from

The cookies last for 30 days, so even if someone leaves your site and comes back later, you’ll still capture that original UTM data.

Testing It Out

Here’s how to make sure everything is working:

1. Clear your browser cookies first (fresh start)
2. Visit your site with UTM parameters: yoursite.com?utm_source=test&utm_campaign=test_campaign
3. Navigate to a few different pages on your site
4. Go back to your form
5. The UTM fields should be populated

If you open your browser’s developer console (F12), you can also type UTMTracker.getUTMs() to see what UTMs are currently stored.

Wrapping Up

So that’s it—two scripts and you’re done. Your WordPress site captures and cookies the UTM parameters, passes them along to your GoHighLevel form, and now you can actually track where your leads are coming from.

No more mystery leads. No more guessing which ad campaigns are working. You’ll know exactly what’s driving results.

Hope this helps you track your advertising a little better. It is what it is—but at least now it works.

Warning

Please test this thoroughly on your website before publishing to production sites.  This is code and can conflict with current plugins or other functionality.  We have tested this in our own environment and was safe to use but every site is different.  If you do experience issues please go back into your functions.php file and your GHL form and remove the snippet of code and your site should resume back to normal use.  

Share This Post :

Discover Latest Trends

in Our Blog Hub