DEV Community

Shweta Danej
Shweta Danej

Posted on • Edited on

3

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

API Trace View

How I Cut 22.3 Seconds Off an API Call with Sentry 👀

Struggling with slow API calls? Dan Mindru walks through how he used Sentry's new Trace View feature to shave off 22.3 seconds from an API call.

Get a practical walkthrough of how to identify bottlenecks, split tasks into multiple parallel tasks, identify slow AI model calls, and more.

Read more →

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay