Drop Table From WordPress Database on Plugin Deactivation

Reading Time: 3 minutes
3,330 Views

Inside this article we will see how to drop table from wordpress database on plugin deactivation. Article contains very classified information about removing dynamic tables on plugin deactivation.

After this article you will be sure how to delete database tables. We usually drop tables when we create those tables for custom plugins. So on plugin removal we also need to remove dynamic tables too.

Apart from dropping tables also we can add more functions which we want should be executed at the time of deactivation.

WordPress works on the basis of filters and hooks. WordPress also provides a deactivation hook. We will see here into complete detail.

Learn More –

Let’s get started.


Plugin Deactivation Hook

WordPress provide a hook for deactivation. We use this deactivation to drop all functions that we have added on plugin activation or theme activation.

register_deactivation_hook(__FILE__, callback);

callback function contains all code which will be executed when plugin/theme deactivates. We will add our logic here which removes all functions.


Code To Drop Table

Here, is the code you can add into your theme file like functions.php or inside your custom plugin.

// plugin deactivation hook
register_deactivation_hook(__FILE__, 'mytable_deactivation_function');

// callback function to drop table
function mytable_deactivation_function()
{
    global $wpdb;

    $wpdb->query("DROP TABLE IF EXISTS " . owt_create_my_table());
}

// returns table name
function owt_create_my_table()
{
    global $wpdb;
    return $wpdb->prefix . "mytable";
}

$wpdb->prefix returns your database prefix. Like in most cases it will be wp_.

To drop wp_mytable database table –

$wpdb->query("DROP TABLE IF EXISTS " . owt_create_my_table());

Successfully we have dropped a table. You can add more drop code here. Also more functions you want you can add it on deactivation.

We hope this article helped you to learn Drop Table From WordPress Database on Plugin Deactivation Tutorial in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Sanjay KumarHello friends, I am Sanjay Kumar a Web Developer by profession. Additionally I'm also a Blogger, Youtuber by Passion. I founded Online Web Tutor and Skillshike platforms. By using these platforms I am sharing the valuable knowledge of Programming, Tips and Tricks, Programming Standards and more what I have with you all. Read more