sitespecificplugin

Create a Simple Plugin in WordPress – 2 – activation, deactivation & uninstall hooks

In this lesson, we will create a table on activate hook, truncate table on deactivate hook and delete table on uninstall hook.

You can download plugin zip files from this git repository.

Just to create new table & insert a raw into table using below code:

function testplugin_activation()
{
    global $wpdb, $table_prefix;

    $tblname = $table_prefix . 'emp';

    $q = "CREATE TABLE IF NOT EXISTS .`$tblname` (`id` INT NOT NULL AUTO_INCREMENT , `name` VARCHAR(100) NOT NULL , `email` VARCHAR(100) NOT NULL , `status` INT NOT NULL DEFAULT '0' , PRIMARY KEY (`id`)) ENGINE = InnoDB;";

    $wpdb->query($q);

    $q = "INSERT INTO `$tblname` (`id`, `name`, `email`, `status`) VALUES (NULL, 'Dilip', 'dilip@gmail.com', '1');";

    $wpdb->query($q);

 // To insert the value using wordpress method to sanitize the values inserted.

    $data = array(
        "name" => 'Janakba',
        "email" => 'janak@gmail.com',
        "status" => 1
    );
    $wpdb->insert($tblname, $data);
}

To truncate the table when plugin is deactivated, we use below code:

function testplugin_deactivation()
{
    global $wpdb, $table_prefix;

    $tblname = $table_prefix . 'emp';

    $q = "TRUNCATE TABLE `$tblname`";

    $wpdb->query($q);
}

In uninstall.php we use below code which will remove the table from database.

global $wpdb, $table_prefix;

$tblname = $table_prefix . 'emp';

$q = "DROP TABLE IF EXISTS `$tblname`;";

$wpdb->query($q);

That’s it for this lesson.