4

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?

  • @Rarst's answer is correct, but why do you want your class name to not be in the global namespace? – Andrew Bartel May 17 '13 at 22:32
  • @AndrewBartel Helps avoid variable conflicts. I can always use $my_class = new my_class; within a function and be sure that scope of $my_class remains within the function. – John May 17 '13 at 22:38
5

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'));.

  • Where does the hook go? Does it go inside of the construct in the class or outside of the class? Doesn't appear to be working for me. – John May 17 '13 at 21:35
  • @John if outside replace __CLASS__ with actual class name as string. If you need to use construct you have to create object with new. This is more of PHP stuff than WordPress. – Rarst May 17 '13 at 22:01
  • Yeah, this definitely is more of PHP stuff, but I was looking for an answer in WP context. Moving the hook outside of the class was first thing I did earlier. But my bad, I was missing the quotes around the class to treat it as a string. I need some coffee now. Thanks for the help. Much appreciated. – John May 17 '13 at 22:35
1

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.

class AjaxEndpoint {
    //Loop through all functions and add them as ajax actions
    public function registerActions() {
        foreach ( get_class_methods( $this ) as $method_name ) {
            if ( $method_name !== 'registerActions' ) {
                add_action( "wp_ajax_".$method_name, array( $this, $method_name ) );
                //add_action( "wp_ajax_nopriv_".$method_name, array( $this, $method_name ) );
            }
        }
    }

}

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.