1

I´m writing an addon. I would like in the install function to stop the activation if the main plugin is inactive.

class MyAddon {

     public function __construct(){
         register_activation_hook( __FILE__, array( $this, 'install' ) );
     }

     public function install(){
        if ( is_plugin_inactive( 'MainPlugin.php' ) ){
           //The addon has to be inactive
           // Notice for admin to prevent to active the main plugin before.
        }
    }

}

How can I do this ?

1 Answer 1

0

I found the solution.

First of all, I discover that...

you cannot use the admin_notices hook inside the activation hook function. More details here

Thanks the link above, I found this solution :

class MyAddon {

    const ACTIVATION_ERROR = "foo-activation-error"

    public function __construct(){
        register_activation_hook( __FILE__, array( $this, 'install' ) );
        if( is_admin() ){
            add_action( "admin_init", array( $this, "init" ), 2 );            //priority 2 to load after the plugin
        }else{
             add_action( "init", array( $this, "init" ), 2 );
        }
    }

    public function init(){

        $has_to_be_deactivate = get_transient( self::ACTIVATION_ERROR );
        if( is_admin() ){
            if( $has_to_be_deactivate ){
                add_action( 'admin_notices', array( $this, "display_warning_no_activation" ) );
                deactivate_plugins( plugin_basename( __FILE__ ) );
            }
        }
    }

    public function install(){
        if ( is_plugin_inactive( 'MainPlugin.php' ) ){
            set_transient( self::ACTIVATION_ERROR , true );
    }

    public function display_warning_no_activation() {
        if( get_transient( self::ACTIVATION_ERROR ) ){
           ?>
           <div class="notice notice-error" >
              <p><?php echo esc_html__("Impossible to activate the addon : « My Addon », please check if the plugin « My Main Plugin » is active!", "addon-domain" ); ?></p>
          </div>
          <?php
       }
       delete_transient( self::ACTIVATION_ERROR );

    }
}

}

1
  • I dunno if this is the solution, but I'm looking at a similar challenge and this certainly seems to be a valid approach.
    – TonyG
    Commented Jul 23, 2021 at 18:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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