Check out the "Digging into wordpress book by: "by Chris Coyier and Jeff Starr."

How to Get Your Wordpress Plugin To DROP TABLE From The Database

Posted on January 28, 2010 by Marty

I’m going to show you an easy way, how to get rid of your database tables & options when the plugin is deactivated, that’s if you want them deleted?

Wordpress - Do you need Help?

If you’ve ever made a plugin or thought about making a plugin for wordpress which includes its own set of database tables, then the chances are (like most plug-ins) they wont remove the data when the plug-ins been de-activated.

In most cases this is to preserve the data in those tables, Just in case the user wants to reactivate the plugin with all the options still saved, or in other case’s, it’s just plain lazy?

The Function

<?php
function pluginUninstall() {
  global $wpdb;
  $thetable = $wpdb->prefix."your_table_name";
  //Delete any options that's stored also?
  //delete_option('wp_yourplugin_version');
  $wpdb->query("DROP TABLE IF EXISTS $thetable");
}
?>

What you have to do is hook this Function into wordpress.
So when the plugin is de-activated you want this code to run…

The Hook

To do this, we call…

register_deactivation_hook($file, $function)

This wordpress function takes 2 parameters in order for it to work…

  1. The File to be called
  2. The Function to run

Example:

If your plugin is located in either of following locations
http://www.yourblog.com/wp-content/plugins/yourplugin.php or

http://www.yourblog.com/wp-content/plugins/yourplugin/plugin-name.php

then you can use this..

register_deactivation_hook( __FILE__, ‘pluginUninstall’ );

The __FILE__ will point to were your function is located, (The Current File your working in) and the 2nd part after the comma is the name of the function which is being passed, in this case were calling our pluginUninstall function, this will then remove all the options and tables that’s been added in the function.

Preserve Your Data

If your plugin needs to/or you want it to, keep some form of data behind after its de-activated, then you can simply write another function to handle that request, maybe you have an admin options page for your plugin? on there you can add a small section with a form, this can just have a button, which when pressed it can run the function and remove whatever data you would like…

You know of any other way? feel free to share!

Leave a Reply