Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WordPress Plugin Development - Can't drop database table after plugin deactivation?

I am trying to drop the database table created when my custom plugin is activated. I am using basically the same code, just a drop query. However, the table won't drop!

I have confirmed the following:

  • The WP Database User has privileges to drop tables (I confirmed by running sql query in workbench)
  • The query is being called and is correct (I used 'die($sql)' to output the query, then ran it in workbench)

    function my_plugin_remove_database() {
         global $wpdb;
         $table_name = $wpdb->prefix . "my_plugin_table";
         $sql = "DROP TABLE IF EXISTS $table_name;";
         //die($sql);
         require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
         dbDelta( $sql );
         delete_option("my_plugin_db_version");
    }
    register_deactivation_hook( __FILE__, 'my_plugin_remove_database' );
    
like image 608
JimmyJammed Avatar asked May 31 '13 19:05

JimmyJammed


People also ask

What is Dbdelta in WordPress?

Modifies the database based on specified SQL statements.

How do you check a table is exist or not in WordPress?

By default, WordPress uses this class to instantiate the global $wpdb object, providing access to the WordPress database. The actual line that checks if table already exists or not is inside if statement. This statement return true if there is no table with the name $table_name and vice versa.


1 Answers

Use $wpdb->query() instead of dbDelta()

function my_plugin_remove_database() {
     global $wpdb;
     $table_name = $wpdb->prefix . "my_plugin_table";
     $sql = "DROP TABLE IF EXISTS $table_name;";
     $wpdb->query($sql);
     delete_option("my_plugin_db_version");
}

register_deactivation_hook( __FILE__, 'my_plugin_remove_database' );

dbDelta() does not supported DROP TABLE query.

like image 132
Faishal Avatar answered Oct 13 '22 11:10

Faishal