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
?