# 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.

- Type: PHP
- Runs: Frontend only
- Category: [Analytics & Tracking](https://wpide.com/library/category/analytics/)
- Tags: utm, attribution, forms, marketing
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/analytics-utm-capture/

## Code

```php
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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Remember UTM Parameters and Fill Hidden Form Fields" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
