Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.