WordPress member notification

PHP only runs when you request a page. When the request is over, everything is gone. It’s not like a Node application where the same program handles all the requests and variables can persist across pages just by defining them, so doing things with a $wp_session variable will only do things on that request.

If you navigate to another page, it has to load WordPress again from scratch, and figure everything out fresh. This is why your code doesn’t work, and that’s how all PHP programs work.

If you want to persist something, you have to store it somewhere, such as the database, the filesystem, or an object cache. That’s what things like user meta for logged in users are used for.

There is 1 exception, PHP Sessions using $_SESSION variables, but, they’re not used by WordPress and need some setup. Additionally, they’re incompatible with page caching solutions such as Varnish, Supercache, etc. Additionally, not all hosts support it. For example, PHP Sessions will not work correctly on WP Engine.

Other notes:

  • In PHP variables begin with $ but yours don’t for some reason. I would have expected PHP fatal errors.
  • Global variables need to be declared before they’re used
  • You’re doing an SQL query then dumping the result in a variable with no error processing which is a security risk
  • You’re displaying the result of that query without any formatting or escaping, which is also a security risk
  • You need to end each statement in a ;, your show notification example doesn’t do this, and will generate syntax errors
  • wp_session is never created anywhere, so initially it’s completely undefined. This will generate warnings and notices at runtime that fill your PHP error log