Site icon N77 Design | NickClaeboe.com

Carry Variables From One Url To The Next PHP WordPress Tip Hack

While using WordPress and running traffic to many WordPress sites, I discovered the need for variables to be passed from one page to the next as a visitor is navigating a WordPress site.

After doing some extensive research, I found a simple script that can be added to the theme functions.php file to carry dynamic variable from one page to the next as a visitor is on your site.

I’m my case, I wanted the “utm_source” variable “GA” be appended and carried at the end of my url. It would look something like this:

http://www.mywebsite.com/category/site/?utm_source=GA

What natively happens in WordPress , is that once a visitor clicks a link, the variable is dropped from the url and not carried/passed on to the next page. The following script, when placed in your theme functions.php file, will allow your WordPress theme template to keep that variable and pass it to the next page.

////////////////////////////////////////
///// pass vars page to page

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

/////////////////////////////////////////////////////////

Just replace CUSTOM and PARAM1 with the variables you’re using, in my case, CUSTOM = utm_source and PARAM1 = GA, in the above code and add it to your functions.php

Also, if you are needing to do this for more that one variable, simply duplicate the code and update the variables, but, be sure to create new function identifier as follows:

function wprdcv_param_redirectTWO(){
if( !is_admin() && !isset($_GET['CUSTOM2 ']) ){
$location = "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
$location .= "?CUSTOM2 =PARAM2 ";
wp_redirect( $location );
}
}
add_action('template_redirect', 'wprdcv_param_redirectTWO');

Be sure to test everything out and if you run into any errors, roll back your edits until you get it the way you want it.

Good luck!

 

Exit mobile version