Drop Table From WordPress Database on Plugin Deactivation

Share this Article
Reading Time: 3 minutes
839 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.

Buy Me a Coffee

Online Web Tutor invites you to try Skillshare free for 1 month! Learn CakePHP 4, Laravel APIs Development, CodeIgniter 4, Node Js, etc into a depth level. Master the Coding Skills to Become an Expert in Web Development. So, Search your favourite course and enroll now. Click here to join.

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.

Was this post helpful?

Learn Web Development Courses Risk Free @ $5 only.
Web Development Courses @ $5