Registering AJAX actions

Estimated reading: 3 minutes

Toolbox 1.4.0 adds an easier way of registering action-hooks for AJAX requests. Using Twig templates with headers, you can automatically let Toolbox register multiple AJAX actions, with a number of privacy respecting options.

Registering an AJAX action

Registering a call is easy, just add the following header to a Twig template created in the Twig Templates section of your WordPress Dashboard (needs to be activated in Settings > Toolbox):

  TemplateType: htmx
  Action: my-ajax-call
<h3>This is my first AJAX call</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ratio enim nostra consentit, pugnat oratio. Quonam, inquit, modo? Quis istud possit, inquit, negare? Quid vero? Hoc mihi cum tuo fratre convenit. Est, ut dicis, inquit; Tamen a proposito, inquam, aberramus.</p>

The TemplateType header obviously tells it that it’s going to be a htmx/ajax call.

By adding the Action header, you can add a custom action name, which you can change any time you want. If not provided, it will use the slug created for the template.

If you were to call out to this action on your server, you’d typically do that on an address like this:

If your server is live and you’ve added the template depicted above, calling out to your server’s url and path mentioned above should return the html for the heading and paragraph!

More headers

To ensure more security there are a few other headers that can be used:

  TemplateType:   htmx
  Action:         my-ajax-call
  Privacy:        nopriv priv
  Roles:          administrator editor
  OnFilter:       my-filter-hook


Using this header, you can set if the hook needs to be registered for priv (logged in users), nopriv (all visitors) or both. If no header is added, it assumes it will be authorized for both priv and nopriv alike.


Typically this is set on a action that is also marked as a Privacy: priv template. If more granular control is needed who can request this template, setting a role here is probably a good idea.


If you need more checks, you can enter a custom filter hookname here.

The filter will be applied and depending on its result it will render the template, return an alternative string or will not be able to render anything.


add_filter( 'my-filter-hook' , 'show_call_or_not' , 10, 4 );

function show_call_or_not( $allow, $file_headers, $roles, $slug ) {
  // if user is logged in, allow it
  return user_is_logged_in();

More complex AJAX actions

Of course, you might have more complex requirements for your AJAX calls. Move to the next doc for some more advanced implementations of such calls.

Share this Doc

Registering AJAX actions

Or copy link