简体   繁体   中英

How to pass custom variable as URL parameter in WordPress

We have started appending fairly simple custom parameters onto the url of our website to track marketing sources. An example might be www.example.com?campaign=facebook&device=mobile.

Problem is, WordPress blocks these custom parameters from pushing from one page to the next. I've read that there is a way to either (1.) add a cookie to store these parameters until the application is being filled out or (2.) add some code to the PHP of the WordPress site that will make it recognize these parameters and allow them to push through. I would imagine that #2 is easier to do, but I really don't know.

I found this code:

function add_query_vars_filter( $vars ){
  $vars[] = "campaign";
  return $vars;
}
add_filter( 'query_vars', 'add_query_vars_filter' );

But it does not seem to be working. I'm not sure if I'm miswriting the code, putting it in the wrong spot, or using the wrong thing altogether. I put it in the functions.php file of the WordPress site. Any help would be greatly appreciated!

I would definately go with option one and set a cookie as soon as the page loads. You don't want a query string variable following you around every link on the website.

First, check for the $_GET request and save a cookie if it is set.

if (isset($_GET['campaign']){ 
   setcookie("campaign", $_GET['campaign'], time()+3600);  /* expire in 1 hour */
}

Then check if the cookie is set and edit your business logic accordingly.

if(isset($_COOKIE['campaign'])) {
echo "Welcome back it looks like you came from the '" . $_COOKIE['campaign'] . "' campaign!";
}  

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM