June 17, 2024

Fixing WordPress `400 Bad Request` on admin-ajax

This is for future me and any developer that might bump into this issue in the future. If I can save 10% of the time I spent debugging and testing solutions for this, I’ll be more than happy.

Say you have a custom AJAX call from the frontend of your site. In WordPress this might look like this:

add_action('wp_ajax_nopriv_get_custom_areas', 'App\View\Components\Comp::getCustomAreas');

Somewhere in a JavaScript file, you’ll probably have a fetch call to wp-admin/admin-ajax.php, but that’s not the issue, so stop looking there.

After triggering that call, I was randomly getting 400 Bad Request errors. Open an incognito tab: worked great. Safari? Great. Client’s browser? Failed. But not always. Cleared cache and it worked.

After taking a few days’ vacation, I came back fresh to the problem and started googling again.

The Problem

The issue was as simple as: logged in users’ call was always failing. Turns out wp_ajax_nopriv_custom_call assumes this function is getting called by non logged in users (that’s the nopriv string).

The Solution

Simple. Just add a new action for logged in users:

add_action('wp_ajax_nopriv_get_custom_areas', 'App\View\Components\Comp::getCustomAreas');
add_action('wp_ajax_get_custom_areas', 'App\View\Components\Comp::getCustomAreas');

Source links: