Wondering if its possible to deactivate a plugin in the deactivation code of another plugin?
IE. i have a widget that i'm adding via its own plugin that won't function if the 'master' plugin isn't activated...
Yes, register a deactivation hook in your first plugin, and inside this hook deactivate the 2nd plugin using the deactivate_plugins()
function
Note: After writing this, I submitted a trac ticket, only to be told that this one already existed.
@OneTrickPony's answer didn't work forme, and after inspecting the source (specifically deactivate_plugins()
) I found why:
Let's suppose B depends on A, and A is deactivated by the user. WordPress calls deactivate_plugins(A)
.
This function does the following:
deactivate_A
(which we hook onto using register_deactivation_hook
)Now at step 4, we call deactivate_plugins(B)
to deactivate. The same process happens again, and is completed- that's fine. But once that's completed we proceed to step 5 (in the original deactivate_plugins()
call for A). The array is updated to the database - but this array was the very original one retrieved in step 1 and only has A removed. In particular we retrieved it at the beginning when B was still active, and so it contains B.
Note: your deactivation callbacks are fired, even through WordPress still thinks its active next time the page loads.
The solution is to use a later hook (after the option has been updated). For this we can take advantage of the update_option_{$option}
hook:
//This goes inside Plugin A.
//When A is deactivated. Deactivate B.
register_deactivation_hook(__FILE__,'my_plugin_A_deactivate');
function my_plugin_A_deactivate(){
$dependent = 'B/B.php';
if( is_plugin_active($dependent) ){
add_action('update_option_active_plugins', 'my_deactivate_dependent_B');
}
}
function my_deactivate_dependent_B(){
$dependent = 'B/B.php';
deactivate_plugins($dependent);
}
update_option_active_plugins
in plug-in B (your plug-in) and check the array for your dependencies (e.g. plugin A). If it's not there, and your plugin is, deactivate it. But I would advise against this. If I activate plugin B without A, it'd just immediately be deactivated. A better UX would be to have your plug-in to do nothing expect display a message prompting the user to install/activate A. You can even provide a activate link if its installed.
Commented
Dec 8, 2018 at 22:27