I'm trying to create a basic affiliation system plugin that for now, will do the following:
- If it exists, read a $_GET URL parameter in any page (for instance http://mysite.com/about/?affid=1234). If not skip the following two steps.
- Save it in a cookie
- Redirect to a clean URL (http://mysite.com/about/)
My issue lies with the first and last parts (reading the parameter and redirecting). I don't think that add_query_var is the correct way to go with, since I just want to track the referral and not se the parameter in a query. Any thoughts?
Edit: here's what I have until now:
add_action( 'template_redirect', 'test_redirect' );
function test_redirect() {
global $wp;
$wp->add_query_var('aff_id');
//cookie related stuff goes here
$current_url = add_query_arg( $wp->query_string, '', home_url( $wp->request ) );
//strip the URL parameter aff_id from $current_url???
wp_redirect( $current_url ); exit;
}
Edit: Working code, thanks to all of you and specifically @Max who helped a lot.
<?php add_action('init', 'affiliate_redirect');
function affiliate_redirect() {
$varname = 'aff_id';
$weeks = '4';
if( isset($_GET[$varname]) && '' != $_GET[$varname] ) {
setcookie('wp_affiliate', $_GET[$varname], time()+648000*$weeks, '/');
$pageURL = 'http';
if ( isset( $_SERVER["HTTPS"] ) && strtolower( $_SERVER["HTTPS"] ) == "on" ) {
$pageURL .= "s";
}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
$url = preg_replace('/([?&])'.$varname.'=[^&]+(&|$)/','$1',$pageURL);
$last = $url[strlen($url)-1];
if ($last == '?') {
$url = substr_replace($url ,"",-1);
}
wp_redirect($url);
exit;
}
} ?>
isset()
to determine if$_GET['affid']
is set and PHPheader('Location: http://mysite.com/about/')
to redirect.send_headers
is appropriate.