Last week I posted about grabbing Google UTM tags from a url string and using that to hide or show specific content based on a variable. After that task, I kept running into another issue with Google UTM tags… Grabbing them from an incoming link, grabbing those variables, and passing each of them along in the url to each page that the visitor navigates.

At first I was searching for a plugin or a WordPress function to rewrite the url’s with my url string but kept getting nowhere.

After several hours of research and a day later, I found a javascript/php hack that produced the results that I was ultimately looking for. Yes, it could be prettier but it WORKS!

Locate your template footer.php file in your theme folder and place the following code just before the closing tag to grab Google UTM tags and pass them to each page of your WordPress site.

Here’s 5 of the most common Google UTM tags that we grab from the session:


<?php $utm_source = isset($_GET['utm_source']) ? $_GET['utm_source'] : ""; ?>
<?php $utm_medium = isset($_GET['utm_medium']) ? $_GET['utm_medium'] : ""; ?>
<?php $utm_campaign = isset($_GET['utm_campaign']) ? $_GET['utm_campaign'] : ""; ?>
<?php $utm_term = isset($_GET['utm_term']) ? $_GET['utm_term'] : ""; ?>
<?php $utm_content = isset($_GET['utm_content']) ? $_GET['utm_content'] : ""; ?>

<script type="text/javascript">
jQuery(document).ready(function ($) {
$(function() {
$("a").attr('href', function(i, h) {
return h + (h.indexOf('?') != -1 ? "&utm_source=<?php echo $utm_source; ?>&utm_medium=<?php echo $utm_medium; ?>&utm_campaign=<?php echo $utm_campaign; ?>&utm_term=<?php echo $utm_term; ?>&utm_content=<?php echo $utm_content; ?>" : "?utm_source=<?php echo $utm_source; ?>&utm_medium=<?php echo $utm_medium; ?>&utm_campaign=<?php echo $utm_campaign; ?>&utm_term=<?php echo $utm_term; ?>&utm_content=<?php echo $utm_content; ?>");

The first 5 snippets of php code are how you grab the Google UTM tag variables from the incoming link.

As you can see, we are grabbing the variables from the session that being passing in from the link. We’re grabbing the dynamic variable and echoing that variable in the javascript below it.

The javascript is where the magic happens on page redirect.

When a visitor clicks on any internal site link, the variables are picked up from the session and echoed behind the hardcoded variable tokens.

Sidenote: the code can be optimized, but this down and dirty method works