When working with Ajax in WordPress, the general setup is pretty straightforward:
ajaxurl, if needed
And the front-end may refer to the Dashboard, the public-facing part of the blog, or the both. It depends on the nature of what you’re working on.
If you’ve worked with Ajax in WordPress in-depth for any amount of time, then you’re likely familiar with the above process. You’re also familiar with the challenges of maintenance depending on how the code was setup.
If you’re just getting started, then perhaps this post will help shortcut some of the learning the rest of us have had to do.
I don’t think the Ajax APIs are that bad. I know – this is subjective. But from the a maintenance standpoint I believe that there’s at least one thing we can do to make development and maintenance easier.
Separating Files with Ajax in WordPress
The short of it:
Keep the server-side callback functions in their own PHP file.
That is, don’t mix these functions in with other functions in files like
Regardless of the complexity of what you’re building, I’m a big fan of small functions and lean files. To achieve this, it requires that we give some thought to the code that we’re writing.
Reasons For Organization
And when we’re writing functions that the client will call via Ajax, it’s easier if those functions are in their own file.
wp_ajax_hook. This includes functions for the dashboard and the public-facing view of the site.
So how do we do this?
A Strategy For Organization
There’s no hard and fast rule for how to do this – only suggestions. To that end, this is what I’ve found to be useful in the work I’ve done in the past few years:
I don’t know what your naming conventions are or how you typically organize your files. But I do think it’s important to segment functionality based on where it works with WordPress.
When you inherit code from another developer or you have to revisit this code, having it segmented based on responsibility goes a long way in saving time and making it easier to understand regardless of what you’ll actually be doing with the code.
Keeping Separate Files for Ajax in WordPress was written by Tom. For more information about WordPress, development, and resources then visit Tom McFarlin’s blog.
Read more here:: Keeping Separate Files for Ajax in WordPress