Adding UTM parameters to links is useful for tracking marketing efforts, e.g. if you have a banner or an email with links to a landing page, you’ll want to know which method (banner or email) generated the most page visits and form fills. Google has a campaign URL builder that will generate URLs with UTMs for you. In Google Analytics, you can find pageviews to the landing page by UTM parameter. However, if you want to track any subsequent pages after the landing page, then you’ll need a way to pass the UTMs along to the subsequent pages. In my particular situation, I needed to pass UTMs to a 3rd-party site. The visitor flow would be like this
- Click a banner on the home page of example.com. The banner has UTMs in the query string, e.g. example.com/landing-page?utmsource=home-page-banner
- Land on an overview page on example.com, e.g. example.com/landing-page
- Maybe visit other pages on example.com
- Return to example.com/landing-page
- Click a link to register for something on a 3rd-party site, e.g. foo.com/register
By default, only the first pageview of example.com/landing-page would include UTMs in the URL. To pass the UTMs to the link to the 3rd-party site, something extra needed to be done. I chose the following approach, which works well.
- If a URL contains UTM params, save the UTM name/value pairs as session cookies, overwriting any existing UTM cookies.
- If a page has any <a> tags with the class “appendUTM”, then rewrite the href value by appending the UTM params.
I then added the class “appendUTM” to any links where I wanted to append the UTMs. In my case, it was the links to the 3rd-party registration site.
Below is the code that accomplishes this.