Wordpress - Delete tables from database when deleting plugin
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.
Enter code here:
register_deactivation_hook( __FILE__, 'my_plugin_remove_database' );
function my_plugin_remove_database() {
global $wpdb;
$table_name = $wpdb->prefix . 'NestoNovo';
$sql = "DROP TABLE IF EXISTS $table_name";
$wpdb->query($sql);
delete_option("my_plugin_db_version");
}
You need to use register_uninstall_hook
hook instead of register_deactivation_hook
to delete tables from the database.
register_deactivation_hook
fires when we deactivate a plugin and register_uninstall_hook
fires when we want to remove/delete
our plugin.
Please use this code if you have only one table:
function delete_plugin_database_table(){
global $wpdb;
$table_name = $wpdb->prefix . 'table_name';
$sql = "DROP TABLE IF EXISTS $table_name";
$wpdb->query($sql);
}
register_uninstall_hook(__FILE__, 'delete_plugin_database_table');
If you have more than two tables then you use this code:
function delete_plugin_database_tables(){
global $wpdb;
$tableArray = [
$wpdb->prefix . "table_name1",
$wpdb->prefix . "table_name2",
$wpdb->prefix . "table_name3",
$wpdb->prefix . "table_name4",
];
foreach ($tableArray as $tablename) {
$wpdb->query("DROP TABLE IF EXISTS $tablename");
}
}
register_uninstall_hook(__FILE__, 'delete_plugin_database_tables');
Reference Links:
https://developer.wordpress.org/reference/functions/register_uninstall_hook/ https://developer.wordpress.org/plugins/plugin-basics/uninstall-methods/