Why use admin-ajax.php and how does it work?

1) Why use admin-ajax.php instead of encoding your json in a separate
file like themes/example/json.php and encode your data there?

Using admin-ajax.php means that the WordPress Core is loaded and available. WIthout that, you would need to hand load the files you need, which is a complicated process and prone to failure if you don’t know the Core very, very well. And, how good are you with Javascript security?

2) How does admin-ajax.php work? I don’t understand much from that
file. Does it load all the functions so you are ready to use them?

  1. It loads the WordPress Core, meaning you can use things like $wpdb
    and $WP_Query. That is through about line 25.
  2. It sends a few headers– lines 37 – 41.
    1. A content type header
    2. A header to tell browsers not to cache the results
    3. The interesting headers are those sent by send_nosniff_headers()
    4. and nocache_headers().
  3. The admin_init hook fires.
  4. Core actions are defined and registered dynamically– lines 46 – 73.
    These won’t be registered unless they are needed– that is, unless
    they are requested via $_GET or $_POST.
  5. The “heartbeat” API hook fires– line 75
  6. The “logged in” status of the requesting user is checked and the
    appropriate administrative or “no priviledge” hook is fired.

Items #1 and #6 are the primary reasons to use the AJAX API, in my opinion. You have the WordPress Core, which you almost certainly need, and you have the same login security system as with the rest of WordPress.

Leave a Comment