How to init an addon correctly after the main plugin?

The best solution I found to… :

  1. Check if the main plugin is active just before to initialize the addon
  2. init the addon before to add menu item or some hook adding like wp_ajax_my_function

Use the hook plugins_loaded to init addons

Use a function to check in pure PHP classes, functions and constants from the main plugin like here

 namespace MyPlugin;

 class AddonMainClass{

     public function __construct(){
         add_action('plugins_loaded',  array( $this , 'init' ) ); 
     }

     public function init(){
         if( is_admin() ){
              $is_main_plugin_active = $this->detect_plugin(
                array(
                      'classes' => array(   
                              'MyPlugin\\Common\\ClassA',
                              'MyPlugin\\Common\\ClassB'
                      ),
                      'functions' => array(
                              'MyPlugin\\useful_function'
                      ),
                      'constants' => array(
                              'MyPlugin\\PLUGIN_DOMAIN'
                      )
                )
            );
            if ( ! $is_main_plugin_active ) {
               // admin notices    
            }else{
               // Init the addon 
            }
         }
     }
     
     private function detect_plugin( $plugins ) {

         /** Check for classes */
         if ( isset( $plugins['classes'] ) ) {
             foreach ( $plugins['classes'] as $name ) {
                if ( class_exists( $name ) )
                    return true;
             }
        }

        /** Check for functions */
        if ( isset( $plugins['functions'] ) ) {
            foreach ( $plugins['functions'] as $name ) {
                if ( function_exists( $name ) )
                    return true;
            }
        }

        /** Check for constants */
        if ( isset( $plugins['constants'] ) ) {
            foreach ( $plugins['constants'] as $name ) {
                if ( defined( $name ) )
                    return true;
            }
        }

        /** No class, function or constant found to exist */
        return false;

    }

}

Leave a Comment