Admin-ajax not working without WordPress login

I build a simple JSON API in WordPress that is available via a GET request to /wp-admin/admin-ajax.php. All it does is print some constant JSON object. It’s working fine when I’m logged into WordPress. However, after logging out I’m getting a 400 error. The problem is not caused by some syntax error nor does it have to do with browser caching. Also, the “action” parameter is correctly defined as it is working when I’m logged in. What could be the source of the error?

Answer

You need to add an action for the “nopriv” ajax request

add_action("wp_ajax_name_of_function", "name_of_function");
add_action("wp_ajax_nopriv_name_of_function", "name_of_function");

**** UPDATE

When using AJAX with WordPress it is a good idea to leverage the platform’s wp_create_nonce() functionality for a little added security. Using it is easy:

  1. Add the nonce to the page either in an HTML element data- attribute, or a JS variable
  2. Include the nonce value in the AJAX data sent to the server
  3. On the PHP side, check that the nonce value matches

PHP code example

<body data-nonce="<?= wp_create_nonce("nonce"); ?>">
if(wp_verify_nonce($_POST['nonce'], "nonce")) { echo "We're good"; };

Leave a Reply

Your email address will not be published. Required fields are marked *