Delete tables from database when deleting plugin

I created a plugin and want to add a function to delete my tables from the database when a user deletes my plugin. I created a function that deletes tables from the DB when a user deactivates my plugin, but I don’t want that. Here is the code:

// Delete table when deactivate
function my_plugin_remove_database() {
     global $wpdb;
     $table_name = "NestoNovo";
     $sql = "DROP TABLE IF EXISTS $table_name;";
     $wpdb->query($sql);
     delete_option("my_plugin_db_version");
}    
register_deactivation_hook( __FILE__, 'my_plugin_remove_database' );

As you can see, this function deletes tables when the plugin is deactivated, but I need to do that when the plugin is deleted.

6

You could do this using the WordPress uninstall.php support:

<?php
    if( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) exit();
    global $wpdb;
    $wpdb->query( "DROP TABLE IF EXISTS NestoNovo" );
    delete_option("my_plugin_db_version");
?>

This uninstall.php file is called when your plugin is deleted.

Leave a Comment