Tracking UTM Parameters and Referrers in WordPress with JavaScript

utm tracking

Tracking UTM parameters and referrers is essential for understanding the source of your website traffic and the effectiveness of your marketing campaigns. In this article, we’ll explore how to implement this functionality in a WordPress site using a simple JavaScript code snippet.

Overview of the Code

The provided code is written in JavaScript and utilizes jQuery for easier DOM manipulation. The primary purpose of the code is to extract UTM parameters from the URL of the page and store them in cookies, making them available for future use. Additionally, the code records the referrer URL, provided it does not contain a specific domain (in this case, “exampledomain.com”).

The Code Explained

<script>
jQuery(document).ready(function($) {
    function getUTMParams() {
        var params = {};
        var queryString = window.location.search.substring(1);
        var regex = /utm_([^&=]+)=([^&]*)/g;
        var match;

        while (match = regex.exec(queryString)) {
            params[decodeURIComponent(match[1])] = decodeURIComponent(match[2]);
        }

        return params;
    }

    function setCookie(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 + "=" + (value || "") + expires + "; path=/";
    }

    function getCookie(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
        }
        return null;
    }

    var utmParams = getUTMParams();
    for (var key in utmParams) {
        if (utmParams.hasOwnProperty(key)) {
            setCookie('utm_' + key, utmParams[key], 7);
        }
    }

    // Cache referrer URL if it contains "exampledomain.com" in any form
    var referrer = document.referrer;
    var referrerRegex = /exampledomain\.com/i;
    if (referrer && !referrer.match(referrerRegex)) {
        setCookie('referrer', referrer, 7);
    }

    // Fill form fields with UTM parameters and referrer URL
    var utmKeys = ['source', 'medium', 'campaign', 'term', 'content'];
    utmKeys.forEach(function(key) {
        var field = $('input[name="form_fields[utm_' + key + ']"]');
        if (field.length) {
            var cookieValue = getCookie('utm_' + key);
            if (cookieValue) {
                field.val(cookieValue);
            }
        }
    });

    var referrerField = $('input[name="form_fields[referrer]"]');
    if (referrerField.length) {
        var referrerCookie = getCookie('referrer');
        if (referrerCookie) {
            referrerField.val(referrerCookie);
        }
    }
});
</script>

How the Code Works

Extracting UTM Parameters: The getUTMParams function parses the URL to extract all UTM parameters. These parameters are stored in an object called params.

Setting Cookies: The setCookie function creates a cookie for each UTM parameter and saves it for a period of 7 days.

Storing Referrer URL: The referrer URL is stored in a cookie if it does not contain “exampledomain.com”. This is achieved by checking the document’s referrer and using a regular expression to exclude URLs containing the specified domain.

Populating Form Fields: The script looks for form fields that correspond to the UTM parameters and referrer URL. If these fields exist, they are populated with the values from the cookies.

How to Use This Code in WordPress

Insert the Code into Your Theme: Add the code to the header.php file of your WordPress theme, just before the closing </head> tag.

<script>
// Insert the entire JavaScript code here
</script>

Add Hidden Fields to Your Forms: Ensure that your forms have fields for the UTM parameters and referrer URL. For example:

<input type="hidden" name="form_fields[utm_source]" value="">
<input type="hidden" name="form_fields[utm_medium]" value="">
<input type="hidden" name="form_fields[utm_campaign]" value="">
<input type="hidden" name="form_fields[utm_term]" value="">
<input type="hidden" name="form_fields[utm_content]" value="">
<input type="hidden" name="form_fields[referrer]" value="">

Detailed Steps to Implement

Extract UTM Parameters: The script uses the getUTMParams function to parse the URL query string for any UTM parameters (e.g., utm_source, utm_medium, etc.) and stores them in an object for easy access.

Set and Retrieve Cookies: The setCookie and getCookie functions manage the storage and retrieval of cookies. This ensures that UTM parameters and referrer information are stored across multiple sessions for a duration of 7 days.

Handle Referrer URL: The script checks the document referrer to ensure it doesn’t contain “exampledomain.com” before storing it in a cookie. This helps in tracking the original source of traffic, excluding specific domains as needed.

Populate Form Fields: When users fill out forms on your site, the script automatically populates hidden fields with the stored UTM parameters and referrer URL. This is useful for tracking the origin of form submissions and associating them with your marketing efforts.

Conclusion

Tracking UTM parameters and referrers is crucial for gaining insights into the performance of your marketing campaigns. With this straightforward JavaScript implementation, you can effortlessly capture and utilize this data in WordPress. By following the steps outlined above, you can enhance your website’s analytics and make more informed marketing decisions.


Leave a Reply

Your email address will not be published. Required fields are marked *