問題描述

我試圖在激活第一個插件時自動激活第二個插件。

register_activation_hook(__FILE__, 'example_activation' );
function example_activation() {
        include_once(ABSPATH .'/wp-admin/includes/plugin.php');
        activate_plugin('hello.php');
}

它不工作在 register_activation_hook .. 它的工作,如果我直接使用它像:

include_once(ABSPATH .'/wp-admin/includes/plugin.php');
activate_plugin('hello.php');

我該如何解決?感謝幫助

解:

我現在正在使用這個:

// When this plugin activate, activate another plugin too.
register_activation_hook(__FILE__, function(){
    $dependent = 'hello.php';
    if( is_plugin_inactive($dependent) ){
        add_action('update_option_active_plugins', function($dependent){
            /* for some reason, 
            activate_plugin($dependent); 
               is not working */
            activate_plugin('hello.php');
        });
    }
}); 

// When this plugin deactivate, deactivate another plugin too.
register_deactivation_hook(__FILE__, function(){
    $dependent = 'hello.php';
    if( is_plugin_active($dependent) ){
        add_action('update_option_active_plugins', function($dependent){
            deactivate_plugins('hello.php');
        });
    }
}); 

最佳解決方案

有關發生什麼的詳細説明,請參閲 this post(這是用於禁用 plug-ins,但問題是相同的) 。

簡要説明:Plug-ins 通過將其添加到存儲在數據庫中的活動 pug-ins 數組來激活。當您激活第一個 plug-in 時,WordPress 檢索所有當前活動的 plug-ins 的陣列,將 plug-in 添加到它 (但不更新數據庫),然後運行安裝回調。

此安裝回調運行您的代碼。

之後 WordPress 更新數據庫與上述數組,其中包含第一個但不是第二個 plug-in 。因此,您的第二個 plug-in 似乎未被激活。

解決方案:在上述鏈接中提到了解決方案是這樣的 (未經測試):

//This goes inside Plugin A.
//When A is activated. activate B.
register_activation_hook(__FILE__,'my_plugin_A_activate'); 
function my_plugin_A_activate(){
    $dependent = 'B/B.php';
    if( is_plugin_inactive($dependent) ){
         add_action('update_option_active_plugins', 'my_activate_dependent_B');
    }
}

function my_activate_dependent_B(){
    $dependent = 'B/B.php';
    activate_plugin($dependent);
}

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。