What’s the point of using WordPress’s built in admin-ajax.php?

I’m trying to understand why using admin-ajax.php is advantageous over doing something like this:

add_action ('wp_loaded', 'my_ajax');
function my_ajax() {
   // Do Ajax, Check $_POST
   die();
}

With the JQuery ajax just pointing to the blog’s index.

admin-ajax.php seems rather convoluted to do something simple, with having to register scripts and add hooks and set up a js variable url to point to the admin-ajax.php and then with wp_ajax_nopriv_ vs wp_ajax_. Not to mention it’s kind of weird that back end is being mixed with the front end. I’m pretty sure there’s an analogy there.

So why use it? Does admin-ajax.php have less overhead? Is it purely a standards thing? Is there something magical about it? What do you miss out by not using it?

1 Answer
1

First, like many things in WordPress, it’s not like someone decided “let’s make this neat and convenient”. It was more like someone slapped it together for something, then it got used more in admin, then it got used a lot in admin, then it became kind of practice to use it for non-admin as well. Or something along these lines.

Second, it’s not as much what it does, as knowing that it always does same thing. You have no idea what request to the arbitrary part of front end is doing. What if analytics plugin is running, counting it as page view? What if there is complex redirect logic that handles seasonal URLs? What if, what if…

Ajax endpoint is meant for ajax:

  • it declares DOING_AJAX constant for context, many things look for it to skip doing whatever they are doing
  • it sets up HTTP headers and stuff
  • it gives you basic code organization convention, including user/anonymous distinction

Leave a Comment