Each time I have to add an ajax function in a WordPress plugin, I lost time to know what is the problem. So I decided to wrap

add_action("wp_ajax{$function_name }", array( $function_class, $function_name ) )

with a function which check if there is an error.

This is the actual list of reasons why wp_ajax won´t be correctly called :

  • The file where there is the php ajax function does not exist

  • The class where there is the ajax function is not included before doing

    add_action("wp_ajax{$function_name }", array( $function_class, $function_name ) ) 
  • The function or the method inside the class does not exist.

  • The ajax function is added in the wrong moment. If you use a hook like this :

    add_action( "wp_loaded", array( $this, "add_wp_ajax_functions" ) );

    and add

    add_action("wp_ajax{$function_name }", array( $function_class, $function_name ) )

    inside add_wp_ajax_functions() that works, but not for all hooks of course.

So, my question is about the last list point. Which hooks are allowed to use the function add_wp_ajax_functions().

For the moment I know that :

Right hooks

  • wp_loaded
  • ?

Wrong hooks

  • ?

I saw "If you look into this file wp-admin/admin-ajax.php where the wp_ajax_ actions are called, you will find that the admin_init action is being called before it."

So should have added wp_ajax functions before admin_init ?

  • have you considered using the newer more modern REST API instead? The REST API gives you error messages in plain english when something goes wrong, and is a lot easier to work with – Tom J Nowell May 15 at 14:19
  • This is a question in order to create a function which wrap add_action( "wp_ajax_" ). It will be inside my core code for my plugins. I don´t use REST API for the moment because when I will do it, I need to do a big changement. – J.BizMai May 16 at 16:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.