Pass $this to function nested in another public function of the same class

There are multiple ways to accomplish this. I’m showing you a way that will not fundamentally change how you are doing it:

First in My_Plugin class:

class My_Plugin {
    // ...
    private function define_public_hooks() {
        $plugin_public = new My_Plugin_Public( $this->get_plugin_name(), $this->get_version() );
        $this->loader->add_action( 'init', $plugin_public, 'init' );
        // ...
    }
    // ...
}

Then in My_Plugin_Public class, create a new method named init. Here you’ll do things that you want once WordPress init action hook is triggered. So adding shortcode will go into this init method:

class My_Plugin_Public {

    public function __construct( $plugin_name, $version ) {

        $this->plugin_name = $plugin_name;
        $this->version = $version;

    }

    public function init() {
        add_shortcode( 'my_shortcode', array( $this, 'my_plugin_ajax_register_shortcode' ) );
    }

    public function my_plugin_ajax_register_shortcode( $atts ) {
        $content="shortcode content";
        wp_enqueue_script( $this->plugin_name . '_google_maps_api' );
        return $content;
    }
}

So, basically instead of creating an inner function within the class method my_plugin_ajax_register_shortcode, we are utilizing another method named init within the class. Now we’ll be able to access $this->plugin_name inside the shortcode handler function, because now it’s within the scope of our My_Plugin_Public class.

Leave a Comment