When would it be best to hook AJAX functions on a back-end page?

I’m setting up my page as follows:

add_action( ‘admin_menu’, [$this, ‘addAdminMenu’ ], 80 );

And its content:

public function addAdminMenu()
$this->hook_suffix = add_theme_page(
esc_html__( ‘Setup’, ‘setup-theme’ ),
esc_html__( ‘Setup’, ‘setup-theme’ ),
‘manage_options’, $this->setup_page_handle,
[ $this, ‘setupPageContent’ ]

But I also need to initialize a few classes, right in the constructor of my class (where the admin_menu hooks are):

new AJAXRoutinesPluginRoutines();
new AJAXRoutinesContentImportRoutines();

So that, on this page, it can handle user input. The PluginRoutines class works as follows:

class PluginRoutines
public function __construct()

add_action( ‘wp_ajax_parse_install_request’, array( $this, ‘parseInstallRequest’ ) );

But this problematic. This way, these AJAX classes that are specific only to my setup page will get loaded on every page, now, there’s a fix, which I used for my assets:

add_action( ‘admin_enqueue_scripts’, [$this, ‘enqueueSetupPageAssets’] );
public function enqueueSetupPageAssets( $page )
if( $page == $this->hook_suffix ) {
//enqueue all of the page’s assets here.

This works because admin_enqueue_scripts fires after admin_menu, so my hook_suffix is created. But if I were to fire my AJAX classes the same way I do with the assets, it doesn’t work.

Clearly, if I hook them this way, then the wp_ajax_parse-~~ hooks are missed. So AJAX clearly initializes itself very early.

What is a good hook / check to only load them on only this page?

Read more here:: When would it be best to hook AJAX functions on a back-end page?

Leave a Reply

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