如果主插件未激活,如何停止激活插件

时间:2018-10-09 作者:J.BizMai

我正在写一个插件。如果主插件处于非活动状态,我希望在安装功能中停止激活。

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.
        }
    }

}
我该怎么做?

1 个回复
SO网友:J.BizMai

我找到了解决办法。

首先,我发现。。。

您不能使用admin_notices 激活挂钩功能内的挂钩。More details here

感谢上面的链接,我找到了以下解决方案:

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

    }
}
}

结束

相关推荐

Custom WordPress Installation

我想知道下面的帖子中描述的自定义WordPress安装的方法是否有更新版本。http://wpbits.wordpress.com/2007/08/10/automating-wordpress-customizations-the-installphp-way/