I’m not even sure if this is possible. But nevertheless I thought of asking. I’m in habit of wrapping/grouping AJAX calls for a particular need within a class. See below.
class my_class {
function __construct() {
$this->hooks();
}
function hooks() {
add_action('wp_ajax_my_action', array($this, 'my_action_callback'));
}
function my_action_callback() {
// do something
}
}
Now in order for the AJAX callback to work, I must add the following to functions.php
(without wrapping it inside any function) to instantiate the class and make the callback work.
$my_class = new my_class;
This adds $my_class
to the global
namespace. Something that I would like to avoid. Any idea on how I can register the AJAX callback function without instantiating the class in functions.php
?
If you are using class which needs an instance of, you have to create that instance somewhere. Currently WP has no designated convention for something like that.
Common practice is to use static methods, so your hook becomes
add_action('wp_ajax_my_action', array(__CLASS__, 'my_action_callback'));
.Here is an example of a class that I use to automatically create ajax callbacks from methods in the class. It acts almost like a router.