Create Tables in database when wordpress plugin activated

Wanted:

    • I want to create 3 tables when plugin activated
    • The tables name are fahmitut_type, fahmitut_meet and fahmitut_content
    • The code in plugin_folder/admin/fahmi_tutorial_create_tables.php
    • The main plugin file is fahmi_tutorial.php

Question:

How to do it?

Answer:

Create fahmi_tutorial_create_tables.php file inside plugin_folder/admin

Create a function named as fahmi_tutorial_create_tables with content like below:



 function fahmi_tutorial_create_tables() {
    global $wpdb;

    $table_name1 = $wpdb->prefix . 'fahmitut_type'; 
	$table_name2 = $wpdb->prefix . 'fahmitut_meet';
	$table_name3 = $wpdb->prefix . 'fahmitut_content';
    $charset_collate = $wpdb->get_charset_collate();
	$engine = " ENGINE=InnoDB"; 

       
	$sql1 = "CREATE TABLE $table_name1 (
			id INT(11) NOT NULL AUTO_INCREMENT,
			name TINYTEXT NULL DEFAULT NULL,
			status ENUM('Y','N') NULL DEFAULT NULL,
			id_term SMALLINT(3) NULL DEFAULT NULL,
			PRIMARY KEY (id) USING BTREE )
			$charset_collate
			$engine;";
			
	$sql2 =	"CREATE TABLE $table_name2 (
			id INT(11) NOT NULL AUTO_INCREMENT,
			name TINYTEXT NULL DEFAULT NULL,
			status ENUM('Y','N') NULL DEFAULT NULL,
			PRIMARY KEY (`id`) USING BTREE
		)
		$charset_collate
		$engine;";
	
	$sql3 =	"CREATE TABLE $table_name3 (
			`id` SMALLINT(6) NOT NULL AUTO_INCREMENT,
			`id_post` SMALLINT(6) NULL DEFAULT NULL,
			`id_type` TINYINT(4) NULL DEFAULT NULL,
			`id_meet` TINYINT(4) NULL DEFAULT NULL,
			PRIMARY KEY (`id`) USING BTREE
		)
		$charset_collate
		$engine;";


    require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
    
    dbDelta( $sql1 );
	dbDelta( $sql2 );
	dbDelta( $sql3 );
 }

$main_file = dirname(dirname(__FILE__)) . '/fahmi-tutorial.php';
register_activation_hook( $main_file, 'fahmi_tutorial_create_tables' );

Explain:

    • require_once( ABSPATH . ‘wp-admin/includes/upgrade.php’ ), this file required because i will use dbDelta() function
    • dbDelta( $sql1 ) is used to create table in database
    • $main_file is required because register_activation_hook() function must be run inside main file of plugin