Developing a plugin is not a simple matter. It may require quite some time and precision, for there are many things to keep in mind. Due to this, occupied by the issues of functionality, many plugin authors forget to include some less critical, yet appreciated options. Therefore, in this article we are going to consider the techniques of activating, deactivating and uninstalling the plugin. Using those will help to keep things clean, in case the user decides he/she no more needs your piece of software.
Note, adding the aforementioned features is of particular importance if you are creating a complex plugin, which requires its own database tables. In this case it is strongly recommended to clear out the options and contents exclusive to the plugin before it is removed.
First things first, let us start with the activation hook. Registering this function is pretty clear-cut. The key to hooking it in is the register_activation_hook function.
It is important though to keep in mind the installation sequence. In case you are planning to install any default terms or custom post types, make sure that they are registered prior to running the code.
Another function suggested to enable is the deactivation hook. It is used when the customer deactivates your plugin from admin, but does not uninstall it, therefore on this occasion you should not delete all plugin data. There are a few things you can do instead, which include:
- flush rewrite rules;
- remove cron jobs;
discharge roles, etc.
Implementing this function obeys the same logic as that of the activation hook. It can be registered using register_deactivation_hook function.
Finally, let’s take a look at the uninstall hook. This function comes in handy when the user chooses to delete the plugin. In this case you will want to have the following done:
- Delete the database tables created by your plugin;
- Remove the post type data;
Eliminate the settings data.
The way to run a code when a plugin needs to be uninstalled is to create a dedicated uninstall.php file. Once created, it will be automatically used by WordPress to delete your plugin. Here is an example of how the code for such file may look like.
To prevent “headers already sent” errors, make sure to avoid echo, when using any of the discussed hooks. It is also advised for you to take some security measures. The most basic thing that can be done is making sure the user is permitted to run these functions.
P.S. Left with a strong desire to switch from your current CMS solution to another one? Give a try to aisite automated migration service and take your web project a step forward right now.