Registering AJAX callback function that is part of a class without instantiating the class in function.php

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.

Read More
$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?

Related posts

2 comments

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

  2. 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 ) );
                }
            }
        }
    
    }
    

Comments are closed.