A dependency-free PHP API for WordPress admin-ajax.php handlers. One listen() call registers the wp_ajax_* and wp_ajax_nopriv_* hooks for you, and handlers are restricted to logged-in users unless you opt in, so a public endpoint is always a deliberate choice rather than a copy-pasted nopriv line.
Part of Pollora, the Laravel framework for WordPress. In a Pollora project it is already installed: use the
#[Ajax]attribute or thePollora\Support\Facades\Ajaxfacade instead.
composer require pollora/ajaxRequires PHP 8.2+ and WordPress (the adapter calls add_action()).
use Pollora\Ajax\Ajax;
// Logged-in users only (default, wp_ajax_my_action)
Ajax::listen('my_action', function (): void {
wp_send_json_success(['message' => 'It works!']);
});
// Everyone: wp_ajax_* and wp_ajax_nopriv_* (explicit opt-in)
Ajax::listen('public_action', fn () => wp_send_json_success())->forAllUsers();
// Guests only (wp_ajax_nopriv_*)
Ajax::listen('guest_action', fn () => wp_send_json_success())->forGuestUsers();Ajax::listen($action, $callback)returns a fluentAjaxAction; the hooks are registered once the chain completes.- Secure default: logged-in users only.
forAllUsers(),forGuestUsers()andforLoggedUsers()change the audience. AjaxAccessenum:LOGGED,GUESTandALL, for choosing the audience programmatically.Ajax::injectScripts()printsvar Pollora = { ajaxurl: "…/admin-ajax.php" };inwp_head, for front-end requests.- Hexagonal core:
RegisterAjaxActionServiceworks against anAjaxActionRegistrarPort; the WordPress registrar is one adapter.
Inside Pollora, declare handlers with the #[Ajax] attribute; they are discovered automatically:
use Pollora\Ajax\Domain\Model\AjaxAccess;
use Pollora\Attributes\Ajax;
class NewsletterHandler
{
#[Ajax('subscribe')]
public function subscribe(): void
{
wp_send_json_success(['message' => 'Subscribed!']);
}
#[Ajax('load_more', access: AjaxAccess::ALL)]
public function loadMore(): void
{
wp_send_json_success([/* ... */]);
}
}- docs/ajax.md: the security model, the
AjaxAccessenum, front-end JavaScript and script injection. - AJAX in a Pollora project: AJAX.
composer testContributions are welcome: see the contributing guide. Report security issues privately, as described in the security policy.
Pollora Ajax is open-source software licensed under the MIT license. © RuBee group