CHAPTER 7 • Making the Most of WordPress Plugins 195
DATABASE CONTENT AND UNINSTALLING
When creating a plugin that stores data to the database, you need to consider what happens
when someone doesn’t want to use it anymore. Do you need to uninstall functionality to clean
up after yourself? You usually do if you have saved a bunch of things in the database, which
shouldn’t be sitting around full of unused data, anyway.
There are a number of ways to remove unwanted functionality. One method is to include an
uninstall.php file with your plugin. This file contains the uninstall code to delete the database
content you have added:
delete_option( 'my-data' );
This will delete the my-data field in the option database table. Because a lot of plugins
store some option data in that table, it can get cluttered, and that’s never a good thing.
Naturally, you’d add whatever you need to remove to the uninstall.php file. This also applies
for uninstalls made through the WordPress admin interface.
Here’s a dummy uninstall.php:
<?php
// For old versions
if ( !defined( 'WP_UNINSTALL_PLUGIN' ) ) {
exit();
}
// Delete the option data --
delete_option( 'myplugindata_post' );
delete_option( 'myplugindata_feed' );
?>
The first part is a check to see if the uninstall feature is present. This feature was not used in
earlier versions of WordPress, so if you are not using WordPress 3.0 or later (which you of
course should be — that’s some old WordPress you’ve got there, otherwise!), the script will exit,
not doing anything. That way, this file is backward compatible. The remaining code deletes the
option data stored in the database — 'myplugindatapost' and 'myplugindata
feed', in this case. This is done when deleting the plugin from within the WordPress admin
interface; hence, the user gets a cleaned-up database.
The important thing is that you remember to add uninstall functionality should you have stored
anything in the database. You may want to make it optional, however, to remove the data because
it may be useful later on. Also, it is probably a good idea to remove the data on deactivation
because that is recommended for all plugins when doing manual WordPress upgrades.
AFTER UNINSTALLING
It is easy to forget that when a plugin is uninstalled, it may leave a few things lying around.
Database data is one thing, and hopefully the uninstall at least gave the user a chance to clean
up after the plugin, but there is one thing that is even more pressing: shortcodes.