Changing a class state in a wordpress plugin

Is this the right approach to have this kind of behaviour?

No, this kind of behaviour requires a persistant running application that stays in memory, like a NodeJS application, but that’s not how PHP works.

But only updateMembershipPricing does not update the values for an underlaying class MembershipDuration.

It does! But the important thing to note is that they might be the same code but they are not the same object. The object/class with the variable that you updated in your AJAX request died the moment the AJAX request ended and no longer exists.

Every single HTTP request you make to the server starts with a blank slate, loading WordPress and your plugins/themes fresh. At the end of the request everything is wiped clean.

So variables you set on one request do not exist on the next request, there is no continuity. Hooks are added every single time you make a request not just when the code first runs, and variables need to be set up on every single request. Likewise PHP files need to be loaded again too.

This means if you want to set a variable in an AJAX request then use it on a page load, your AJAX request has to store that variables value somewhere persistent then your code needs to retrieve it when needed. This could be in the database, a file, cookies, etc.

When testing this with hardcoded values in a template file it does work fine.

The reason this works is because on every page load it reads in the template file and sees the hardcoded values. These values are persisted in files on the server so they survive the request. Unfortunately because they’re hardcoded they can’t change, and if they did they’d change for everybody which would be a massive security and performance issue.

Where Should I Store Things

  • If it’s specific to the user: User meta
  • If it’s specific to this visitor/session: cookies
  • If it’s specific to a post: a taxonomy if you need to filter/group by it, or post meta for everything else
  • If it’s specific to a site: options
  • If it’s specific to a comment: comment meta
  • If it’s UI state: Store it locally or bundle it into the URL somehow

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)