I am Looking to append URL Parameter to all URLs

I am trying to add URL parameter to all the URLs of WordPress website.

This is for tracking affiliate sales by tracking links.

E.g. I have put a link on another website

http://website.com/?aff=abc

When a person comes to my website via that link the parameter stays in the URL but as soon as the person goes to another page on my website the URL parameter is gone.

I want to keep the parameter in the URL no matter what page the user is on.

I found the following code that works but it works for only one parameter.

function wprdcv_param_redirect(){
if( !is_admin() && !isset($_GET['aff']) ){
    $location = "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
    $location .= "?aff=abc";
    wp_redirect( $location );
}
}

add_action('template_redirect', 'wprdcv_param_redirect');  

Is there a way to modify the above code to have any value in the parameter variable? Right now the value “abc” is fixed for the variable.

4 Answers
4

I don’t know if you still need the answer, but here’s working example for you.

Header.php

/*SAVE $_GET['aff'] TO COOKIE*/
if(!isset($_SESSION['aff']) and $_GET['aff']){
    $cookie_expire = time()+60*60*24*30;
    $_SESSION['aff'] = $_GET['aff'];
    setcookie('aff', $_SESSION['aff'], $cookie_expire, "https://wordpress.stackexchange.com/", '.'.$_SERVER['HTTP_HOST']);
}

Functions.php – if you need to pass one parameter

/*APPEND 'aff' PARAMETER IN URL THROUGH WHOLE SITE*/
function wprdcv_param_redirect(){
    if(isset($_COOKIE['aff']) and !$_GET['aff']){
        $location = esc_url(add_query_arg('aff', $_COOKIE['aff']));
        wp_redirect($location);
    }
}
add_action('template_redirect', 'wprdcv_param_redirect');

OR: Functions.php – if you need to pass array of parameters

/*APPEND 'aff' PARAMETER IN URL THROUGH WHOLE SITE*/
function wprdcv_param_redirect(){
    if(isset($_COOKIE['aff']) and !$_GET['aff']){
        $location = esc_url(add_query_arg(array('aff' => $_COOKIE['aff'], 'parameter_key' => 'parameter_value', 'parameter_key_two' => 'parameter_value_two')));
        wp_redirect($location);
    }
}
add_action('template_redirect', 'wprdcv_param_redirect');

Leave a Comment