Analytics & TestingContent MarketingSearch Marketing

WordPress: How To Append A UTM Campaign Querystring To External Redirects

Martech Zone is often a pass-through site where we connect our visitors with products, solutions, and services available through other sites. We don’t ever want our site utilized as a backlink farm by SEO consultants, so we’re pretty careful in the content we accept and how we redirect our visitors.

Where we can’t monetize an external referring link, we avoid passing any authority to the destination. Again, I don’t want this site ever seen by a search engine as a site where we’re trying to game search engines on behalf of a client or being paid to backlink by an unscrupulous backlinker. Every day we turn down money to do this because the result would spell disaster for my search engine rankings, the trust I’ve built with our readers, and… ultimately… the site’s value.

WordPress Redirects

To manage this process, I utilize Rank Math Pro’s redirection capabilities. It enables me to categorize a redirect to the destination page I want and tracks how much traffic I’m actually sending to the destination. Whether a destination is monetized through a referral link (like the Rank Math link I just shared) or sending traffic without an affiliate link, it enables me to organize, track, and create strategies around the traffic I’m sending.

One of the disadvantages of this is that companies may not be monitoring referral sites within Google Analytics since they could have thousands of sites sending them traffic. Since I’d like to get their attention as a good source of strong traffic, I’d like to append UTM paramers to a campaign querystring so that Martech Zone doesn’t just appear in their referring sites; but appears in campaign tracking within Google Analytics. This way, a company may see how much they’re spending on other campaigns and see the value in possibly building a partnership through a partnership or sponsorship with Martech Zone.

Add a UTM Querystring To Redirects

Rather than editing every redirect I’ve built, this can be automated by looking to see if there’s a UTM parameter already on the destination URL, checking to see if it’s an external link, and appending my site name as the source of the campaign. Some updates:

  • I look for any 3xx HTTP code.
  • I also append any hash fragment (#).
  • I update the redirect type to 302 Found.

So, the result is that a referral redirect coming out of my site that may look like this:

https://martech.zone/refer/company/

Where my redirect destination is:

https://company.com#bookmark

Will now redirect with a 302 to:

https://company.com?utm_source=Martech%2BZone&utm_medium=article&utm_campaign=referral#bookmark

In functions.php in my child theme, I’ve added the following PHP code:

function add_utm_to_redirects($location, $status) {
    if (is_admin() || !$location) {
        return $location;
    }

    // Check if the redirect status is 301
    if ($status >= 300 && $status < 400) {
        // Check if the destination URL is external (outside the site's domain)
        $site_url = site_url(); // Get the site's base URL
        if (strpos($location, $site_url) !== 0) {
            // Parse the URL to extract existing query parameters and the fragment
            $parsed_url = parse_url($location);
            parse_str($parsed_url['query'] ?? '', $existing_params);

            // Check if UTM parameters already exist in the destination URL
            if (
                !isset($existing_params['utm_source']) ||
                !isset($existing_params['utm_medium']) ||
                !isset($existing_params['utm_campaign'])
            ) {
                $site_name = get_option('blogname'); // Get the site name
                $encoded_site_name = urlencode($site_name); // URL encode the site name

                $utm_parameters = array(
                    'utm_source'   => $encoded_site_name, // Use the URL encoded site name as the utm_source
                    'utm_medium'   => 'article', // Set utm_medium to 'article'
                    'utm_campaign' => 'referral', // Set utm_campaign to 'referral'
                );

                // Merge the new UTM parameters with existing parameters, excluding duplicates
                $combined_params = array_merge($existing_params, $utm_parameters);

                $query_string = http_build_query($combined_params);

                // Build the new URL with the combined query parameters
                $new_location = $parsed_url['scheme'] . '://' . $parsed_url['host'] . ($parsed_url['path'] ?? '') . '?' . $query_string;

                // Append the fragment identifier if it exists
                if (isset($parsed_url['fragment'])) {
                    $new_location .= '#' . $parsed_url['fragment'];
                }

                // Perform the redirect with a 302 status code
                wp_redirect($new_location, 302);
                exit();
            }
        }
    }

    return $location;
}
add_filter('wp_redirect', 'add_utm_to_redirects', 10, 2);

Because wp_redirect is a WordPress function, this code will work with any redirection plugin that utilizes that function.

Douglas Karr

Douglas Karr is CMO of OpenINSIGHTS and the founder of the Martech Zone. Douglas has helped dozens of successful MarTech startups, has assisted in the due diligence of over $5 bil in Martech acquisitions and investments, and continues to assist companies in implementing and automating their sales and marketing strategies. Douglas is an internationally recognized digital transformation and MarTech expert and speaker. Douglas is also a published author of a Dummie's guide and a business leadership book.

Related Articles

Back to top button