How can I add a UTM tag with PHP code to pick up the post slug dynamically in the UTM?

The thing I want to do is doable, but I don't know how to do it.

Embarrassment moment coming up: I actually did this a few years ago but lost the code and can't find online how it's done.

What I want to do is to add a dynamic UTM tag on a link in my header so that the UTM tag picks up the slug of the page the visitor is clicking from.

Example: If the visitor is on a post with the slug /something-goes-here/ and clicks on the CTA button, the CTA page that he goes to should have /second-page/?utm_source=something-goes-here

Do you guys know how this can be done with a bit of code in PHP?

Topic google-analytics php Wordpress

Category Web


What comes to mind is getting the current post by global $post, next getting the post slug by $post->post_name, next checking the slug if it needs to update a link with a utm query.

So something like this.

// get the current post
global $post;

// get the post slug, if not set then set it to empty string
$post_slug = $post->post_name ?? '';

// an array of slugs that need to add utm to link
$utm_slugs = [
    'slug-1',
    'slug-2',
    'slug-3'
];

// set default value (empty string), in case no slug was matched
$utm_query = '';

// if post slug exists and in the utm slugs array, set a utm query
if (!empty($post_slug) && in_array($post_slug, $utm_slugs)) $utm_query = '?utm_source=' . $post_slug;

Now that we have the php part taken care of we need to create the link.
This is just an example so change it accordingly.

<a href="http://domain.com/<?= $utm_query; ?>">Some link</a>

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.