我试图在激活第一个插件的同时自动激活第二个插件。
register_activation_hook(__FILE__, \'example_activation\' );
function example_activation() {
include_once(ABSPATH .\'/wp-admin/includes/plugin.php\');
activate_plugin(\'hello.php\');
}
它在register\\u activation\\u 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\');
});
}
});
最合适的回答,由SO网友:Stephen Harris 整理而成
有关所发生情况的完整解释,请参见this post (这是为了停用插件,但问题是一样的)。
A brief explanation: 插件本质上是通过将它们添加到数据库中存储的活动插件数组来激活的。当您激活第一个插件时,WordPress将检索所有当前活动插件的数组,将插件添加到其中(但尚未更新数据库),然后运行安装回调。
此安装回调将运行您的代码。
之后,WordPress用上面的数组更新数据库,其中包含第一个插件,但不包含第二个插件。因此,第二个插件似乎未激活。
Solution: 在上面的链接中提到,解决方案是这样的(未经测试):
//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);
}