Create DB Table On Activating WordPress Plugin

Create DB Table On Activating WordPress Plugin

It provides the instructions to create the database table on activating the WordPress Plugin

January 04, 2021

This tutorial provides the instructions to create the database table on activating the WordPress Plugin. We can create the database table on WordPress plugin activation by checking whether the table already exists in the database. If the table does not exist, we can create the table using the dbDelta function available in the upgrade script as shown below.

Step 1 - Plugin Activation

Add the function to execute on activating the Plugin. I have used myplugin as the plugin name for demonstration purposes.

<?php
/**
* Plugin Name: My Plugin
* Plugin URI: https://www.myplugin.com
* Description: Plugin Description
* Version: 1.0.0
* Author: myplugin
* Author URI: https://www.myplugin.com
* Requires at least: 5.5.1
* Tested up to: 5.5.1
*/

if ( !defined( 'ABSPATH' ) ) exit;

// Act on plugin activation
register_activation_hook( __FILE__, "activate_myplugin" );

// Act on plugin de-activation
register_deactivation_hook( __FILE__, "deactivate_myplugin" );

// Activate Plugin
function activate_myplugin() {

// Execute tasks on Plugin activation

// Insert DB Tables
init_db_myplugin();
}

// De-activate Plugin
function deactivate_myplugin() {

// Execute tasks on Plugin de-activation
}

// Initialize DB Tables
function init_db_myplugin() {

// Code to create DB Tables
}

Step 2 - Initialize DB Tables

Now update the function to create the database table on activating the WordPress Plugin as shown below.

// Initialize DB Tables
function init_db_myplugin() {

// WP Globals
global $table_prefix, $wpdb;

// Customer Table
$customerTable = $table_prefix . 'customer';

// Create Customer Table if not exist
if( $wpdb->get_var( "show tables like '$customerTable'" ) != $customerTable ) {

// Query - Create Table
$sql = "CREATE TABLE `$customerTable` (";
$sql .= " `id` int(11) NOT NULL auto_increment, ";
$sql .= " `email` varchar(500) NOT NULL, ";
$sql .= " `fname` varchar(500) NOT NULL, ";
$sql .= " `sname` varchar(500), ";
$sql .= " `line1` varchar(500) NOT NULL, ";
$sql .= " `line2` varchar(500), ";
$sql .= " `line3` varchar(500), ";
$sql .= " `city` varchar(150) NOT NULL, ";
$sql .= " `state` varchar(150), ";
$sql .= " `area` varchar(15), ";
$sql .= " `country` varchar(5) NOT NULL, ";
$sql .= " PRIMARY KEY `customer_id` (`id`) ";
$sql .= ") ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;";

// Include Upgrade Script
require_once( ABSPATH . '/wp-admin/includes/upgrade.php' );

// Create Table
dbDelta( $sql );
}

}

Summary

This tutorial provided the instructions and example code to create the database table while activating the WordPress Plugin.

Write a Comment
Click the captcha image to get new code.
Discussion Forum by DISQUS