Skip to content 📞 Book Free Call Now
Blog

Boost Campaign Tracking with Dynamic UTM Parameters in WordPress

By Rajan Gupta

• ⏱ 2 min read

Are you struggling to track which pages drive the most conversions? With a simple jQuery script, you can dynamically add UTM parameters to your WordPress buttons—no plugin required. This not only makes your campaign tracking more accurate but also helps you understand user journeys in Google Analytics. In this guide, we’ll show you how to implement dynamic UTM tags step-by-step so every click tells the right story.

<!-- dynamically add page url (path) to the utm_source parameter  -->
<script>
    jQuery(document).ready(function(){
        // get current url and trib trim it to get the page details
            var thispageURL = jQuery(location).attr("href");
            var trimmed_url = window.location.pathname;
            var semi = trimmed_url.replaceAll("/", "_");
            var final = semi.substring(1, semi.length-1);
//             console.log(final);
            // code to get url of consultation button
            var btn_url = jQuery(".sfc_button a").attr('href');
            
            if (final == null || final=='' || final=='_')
            {
                // if parameter is empty
                // code to get url and update the parameter
                var update_url = new URL(btn_url);
                update_url.searchParams.set("utm_medium", "HomePage"); 
                // setting your param
                var final_updated_Url = update_url.href; 
            }
            else{
                // if parameter is not empty
                // code to get url and update the parameter
                var update_url = new URL(btn_url);
                update_url.searchParams.set("utm_medium", final); 
                // setting your param
                var final_updated_Url = update_url.href; 
                
            }
            jQuery(".sfc_button a").attr("href", final_updated_Url); 
            
    });
</script>
Rajan Gupta

Rajan Gupta

FullStack Web Developer

Rajan Gupta is a passionate web developer and digital creator who loves sharing insights on WordPress, modern web design, and performance optimization. When not coding, they enjoy exploring the latest tech trends and helping others build stunning, high-performing websites.