Home > Back-end >  Wordpress Plugin Classes and Ajax
Wordpress Plugin Classes and Ajax

Time:12-14

I'm in desperation, spent 2 days Googling and trying all kinds of ways to do this, but did not succeed.

What I am trying to do.

I want to move some functionalities from my theme to a plugin. I now have a custom page with some rewrite rules to allow for query vars to be passed to page itself (meaning showing different data dependent on passed var). I also have 4-5 Ajax calls running either on click, or on document ready. With moving to plugin one thing I would like to optimize is usage of those query vars in Ajax calls, also share some functions for each call. I would prefer to pass all the functionality from Ajax hooks to methods, not have any data retrieval and calculations inside Ajax functions.

So my general idea is to do this:

  • have a Class for plugin itself to create rewrite rules, enqueue scripts and styles.
  • have a Class for handling HTML templates
  • have a Class for handling Ajax calls / and probably data retrieval from db
  • or also have a separate Class for data retrieval and additional functionalities

Now I have to admit that I'm new to Classes in general and Plugins too.

What I have tried to do:

  1. Load plugin on 'init'
  2. Add rewrite rules, register query vars
  3. If page name matches - enqueue scripts
  4. Get query vars and set them as Class vars
  5. Load html template files as required

What I have problems with is managing Ajax calls. If I add Ajax hook in data retrieval Class, then that Class is launched on every Ajax call and I cant set Class vars. If I add Ajax hooks in separate Ajax Class, then I can't share vars (or I dont know how).

So I'm seeking help. How should I manage my Ajax calls to also be able to use Class vars inside their methods? Maybe I'm going from a wrong side to all of this with Classes?

I hope I made myself clear.

CodePudding user response:

Yeah, so the problem was as I mentioned in my comments to the question: wp_ajax initiates classes as their own instances, so there is no obvious and simple way to share variables except for sending them through Ajax request.

Hopefully this helps anyone else who might come to this question.

  • Related