Bruno Monteiro
Bruno Monteiro

Reputation: 712

How to keep specific URL parameters on links?

I have the following URL:

http://website.com/?utm_source=1&utm_campaign=2&utm_medium=3

When a user access my website with these parameters, all links on my pages get the parameters and merge with their original URL.

So if a link is:

http://website.com/link.html

It will become:

http://website.com/link.html?utm_source=1&utm_campaign=2&utm_medium=3

But my Google Analytics is going nuts with so much data. And I only need to keep utm_campaign.

Is that possible to get only the value of utm_campaign and apply on my URL even if I have others parameters?

Here is my current code:

if (isset($_REQUEST['utm_campaign']) {
    $queryURL = "?" . preg_replace("/(s=[a-zA-Z%+0-9]*&)(.*)/", "$2", $_SERVER['QUERY_STRING'], -1);
    $queryURL = preg_replace("/q=([a-z0-9A-Z-\/])+&(.*)/", "$2", $queryURL, -1);
    $GLOBALS["queryURL"] = $queryURL;
} else {
    $GLOBALS["queryURL"] = 0;
}

Upvotes: 1

Views: 61

Answers (2)

KIKO Software
KIKO Software

Reputation: 16751

Yes, that is possible:

if (isset($_GET['utm_campaign'])) {
  $newUrl = $oldUrl.(strpos($oldUrl,'?') ? '&' : '?').'utm_campaign='.$_GET['utm_campaign'];
}

This piece of code will change the old url to a new url. It takes any parameters of the old url into account. I use $_GET because you don't need $_POST which is also in $_REQUEST.

Upvotes: 0

Barmar
Barmar

Reputation: 781751

Work with the $_GET array rather than the query string:

if (isset($_REQUEST['utm_campaign'])) {
    $query_string = '?utm_campaign=' . $_REQUEST['utm_campaign'];
} else {
    $query_string = '';
}

Then when you create other links, you concatenate $query_string to them.

Upvotes: 2

Related Questions