Remember UTM Parameters and Fill Hidden Form Fields
Saves utm_source, utm_medium, utm_campaign, utm_term, utm_content and gclid from the landing page in a first-party cookie, then fills matching hidden fields in your forms so leads keep their campaign source.
Opens WPIDE on
Code
add_action( 'wp_footer', function () {
?>
<script>
(function () {
var keys = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'gclid', 'fbclid'];
var params = new URLSearchParams(location.search), found = {}, has = false;
keys.forEach(function (k) { var v = params.get(k); if (v) { found[k] = v.slice(0, 200); has = true; } });
if (has) {
document.cookie = 'wpide_utm=' + encodeURIComponent(JSON.stringify(found)) + ';path=/;max-age=' + (30 * 86400) + ';SameSite=Lax' + (location.protocol === 'https:' ? ';Secure' : '');
}
var match = document.cookie.match(/(?:^|; )wpide_utm=([^;]+)/), stored = {};
try { stored = match ? JSON.parse(decodeURIComponent(match[1])) : {}; } catch (e) { stored = {}; }
function fill(root) {
Object.keys(stored).forEach(function (k) {
root.querySelectorAll('input[name="' + k + '"], input[name$="[' + k + ']"], input.' + k).forEach(function (input) {
if (!input.value) { input.value = stored[k]; }
});
});
}
fill(document);
document.addEventListener('focusin', function (e) { if (e.target.form) { fill(e.target.form); } });
})();
</script>
<?php
} );
Notes
Add hidden fields named utm_source, utm_medium and so on to your forms (most form plugins support this). The cookie lasts 30 days and holds only campaign data.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.