keep a variable for all pages in memory from the url

TLDR: Use a cookie

Why Not PHP Sessions?

  • PHP sessions don’t work on most hosts ( e.g. WP Engine which say in their docs they do not support PHP sessions ).
  • PHP sessions are incompatible with caching CDNs, caching proxies such as Varnish, and caching plugins.
  • They rely on a session ID stored in a cookie, so they can’t be used to avoid cookies.
  • There are scaling and security concerns, such as spoofed session IDs, storing sessions across load balanced machines, etc

Why Not Global Variables?

That’s not what global variables are for, or how they work. A global variable lets you change a variables scope so that it can be made everywhere rather than just n that file/functions scope. It has nothing to do with persistence.

To understand why, we have to know that unlike Node applications, PHP programs are loaded from a blank slate every time a page is requested. You can store all the variables you want, but when the page has finished outputting, and the request is over, everything is wiped clean.

This means when you make a request to a WP site, WordPress is loaded from a blank slate, and when the request is finished, it’s unloaded. No variables or loaded code persists across requests, it’s loaded fresh and brand new every, single, time.

So How Do I Persist Something Across a Session?

If you want to store things between requests you have these options:

  • store it in a cookie
  • store it in the database via user meta/posts/custom tables
  • store it externally, e.g. a file, an object cache, remote API
  • put it in the HTML then make sure the data is submitted along with the next request to the site ( e.g. a hidden input in a form )

Because your user isn’t logged in, you should use cookies. If your user s logged in then you can store the referral code in user meta.

If your users are landing on a form and you only need the referral code for the form to be filled out, then put it in a hidden input tag and reprint it out on each page.