11. März 2019

Why I changed from WP AJAX API to REST API – even for non-REST APIS

For years my go-to solution for AJAX calls from the frontend in WordPress was the WordPress AJAX API. The two actions wp_ajax_{action} and wp_ajax_nopriv_{action} create a route that will be accessible from the frontend and the backend and can react on certain parameters being sent via Javascript. This works fine in many circumstances. However there is a caveat in this approach: This hook being fired on the backend the WordPress Conditional is_admin will be true. In most cases this is not a problem but many plugins depend on this function because they don’t want things to change in the backend or vice-versa which is a really sneaky implementation detail because these hooks frequently get fired on AJAX routes too. This caused several hard to track bugs in certain shops I worked on in recent months. Therefore I decided to not use the WordPress AJAX Route for simple AJAX calls again.

To solve this problem I build all new implementations on the WordPress REST API even if that means violating what a REST API actually is (returning HTML is usually a no-go for REST APIs). Using the REST API does not make me dependent on whether the plugins take the is_admin conditional into account or not. As a nice side effect the REST requests are a small percentage faster (~+15%) as their equivalent via AJAX WordPress API as they fire a little less actions.