Problem description
Based on this answer I have made a PHP custom page for WordPress. The page do the follow: when I go to www.mysite.com/wp/GoTo/?URL=http://www.google.com
, the browser redirect to www.google.com
.
The problem is that I would like to use Google Analytics to register the access to the page, in particular when user access a link like the following www.mysite.com/wp/GoTo/?URL=http://www.google.com&utm_campaign=MyChampaign
.
In other words I have my PHP redirect page
<?php
/*
Template Name: GoToPage
*/
/**
*
* @package MyTheme
*/
$url = $_GET["URL"];
// Remove all illegal characters from a url
$url = filter_var($url, FILTER_SANITIZE_URL);
if (filter_var($url, FILTER_VALIDATE_URL)) {
header("location: " . $url);
exit;
} else {
echo("$url is not a valid URL");
}
?>
And I have to insert the Google Analytics snippet.
1st attempt
This doesn't work. I think that the problem is that, for the redirect, I have to output ONLY the header and nothing else.
<?php
/*
Template Name: GoToPage
*/
/**
* The template for displaying all pages.
*
* This is the template that displays all pages by default.
* Please note that this is the WordPress construct of pages
* and that other 'pages' on your WordPress site will use a
* different template.
*
* @package MyTheme
*/
$url = $_GET["URL"];
// Remove all illegal characters from a url
$url = filter_var($url, FILTER_SANITIZE_URL);
if (filter_var($url, FILTER_VALIDATE_URL)) {
<script type="text/javascript" >
window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
ga('create', 'UA-11111111-0', 'auto');
ga('send', 'pageview');
</script>
header("location: " . $url);
exit;
} else {
echo("$url is not a valid URL");
}
?>
2ns attempt
Based on this and this answers I have tried to convert the client side code from HTML to JavaScript code. This gives me a 404 error for every attemp I have made.
<?php
/*
Template Name: GoToPage
*/
/**
* The template for displaying all pages.
*
* This is the template that displays all pages by default.
* Please note that this is the WordPress construct of pages
* and that other 'pages' on your WordPress site will use a
* different template.
*
* @package MyTheme
*/
$url = $_GET["URL"];
// Remove all illegal characters from a url
$url = filter_var($url, FILTER_SANITIZE_URL);
if (filter_var($url, FILTER_VALIDATE_URL)) {
echo """
<head>
<script type="text/javascript" >
window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
ga('create', 'UA-11111111-0', 'auto');
// Plugins
ga('send', 'pageview');
</script>
</head>
<body onload="onWindowLoad()">
<script>
window.location.replace(".$url.");
</script>
<p>If the page does not automatically redirect please click on<a href=".$url.">this link</a>.</p>
</body>
""";
exit;
} else {
echo("$url is not a valid URL");
}
?>
Any idea about how to include the GA snippet in my PHP redirect custom page?