DEV Community

Shweta Danej
Shweta Danej

Posted on • Updated on

WordPress - Create database tables programmatically

<?php

/*
Plugin Name: Demo Plugin
Plugin URI: https://shwetadanej.com/
Description: A simple way to create custom database tables and it's CRUD operations from WordPress admin panel
Version: 1.0.0
Author: Shweta Danej
Author URI: https://shwetadanej.com/
Text Domain: demo-plugin
*/

/**
 * Add function on plugin activation hook
 */
register_activation_hook(__FILE__, 'sd_plugin_activation');

/**
 * Callback function of plugin activation hook
 * This will check if website is multisite or not, if yes then loop through it and create table for each website
 *
 * @return void
 */
function sd_plugin_activation()
{
    $db_created = get_option("sd_db_created");
    if (!$db_created) {
        global $wpdb;
        $table1 = $wpdb->prefix . 'sd_tbl_1';
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $charset_collate = $wpdb->get_charset_collate();
        $table1_query = "CREATE TABLE IF NOT EXISTS " . $table1 . " (
            id int(11) NOT NULL AUTO_INCREMENT,
            user_id int(11) NOT NULL,
            date date NOT NULL,
            time time NOT NULL,
            PRIMARY KEY id (id)
        )$charset_collate;";
        dbDelta($table1_query);

        $table2 = $wpdb->prefix . 'sd_tbl_2';
        $table2_query = "CREATE TABLE IF NOT EXISTS " . $table2 . " (
            id int(11) NOT NULL AUTO_INCREMENT,
            question text NOT NULL,
            answer varchar(50) NOT NULL,
            PRIMARY KEY id (id)
        )$charset_collate;";
        dbDelta($table2_query);
        update_option("sd_db_created", true);
    }
}


Enter fullscreen mode Exit fullscreen mode

Discussion (0)