Using WordPress Plugin Activation Hook to Deactivate Plugin upon Activation by Shu Miyao

Posted on 6 February, 2018

Today I have had a necessity to add a checkup when some of my WordPress plugins are being activated. Sometimes you want to make sure that our plugin is not activated when certain plugins are not activated. Or when PHP version needs to be 7.0 or newer. Or when you simply want to show a Thank you message.

I will focus a scope on a detection of plugin activation and deactivation of the plugin when conditions are met.

The flow is as follows:

  1. Using the WordPress’s register_activation_hook(), run a function only when a plugin of choice is being activated.

    • Use set_transient() of the WordPress Transient API to pass over an information to the next function if conditions are met. Please keep in mind that the information is valid only for the following 5 seconds.
  2. Add an action to ‘admin_notices’ hook, which handles to show a message and to deactivate the plugin when conditions are met.

    • By using get_transient(), check up if there is any data carried over from the register activation hook above. If the value is set to TRUE, it means that the condition is met. Otherwise, let it go.
    • Since the condition is known to be met, show a message.
    • Deactivate the plugin by using deactivate_plugins() function. This function needs to be called here. If you called the function earlier, for example inside the function of register_activation_hook() above, the plugin will not be deactivated.
    • Unset ‘activate’ property of $_GET variable not to show ‘Plugin Activated’ so that the message remains consistent with what we have just done.

That is all. The code is neither that long nor complicated. I made a GitHub repo for you to have a look.


Thank you very much for reading. I hope that this post is helpful!