The first step in making your plugin create database tables automatically is to create a PHP function within your plugin that adds a table or tables to the WordPress MySQL/MariaDB database. For purposes of this article, we’ll assume you want to call this function
custom_plugin.php
function wp_activation_plugin_fun(){
global $wpdb;
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE wp_student (
id mediumint(9) NOT NULL AUTO_INCREMENT,
time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
name tinytext NOT NULL,
address text NOT NULL,
roll_no varchar(500) DEFAULT '' NOT NULL,
PRIMARY KEY (id)
) $charset_collate;";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
// add single demo data into wp_student table
$welcome_name = 'Mr. WordPress';
$welcome_text = 'Congratulations, you just completed the installation!';
$table_name = $wpdb->prefix . 'student';
$wpdb->insert(
$table_name,
array(
'time' => current_time( 'mysql' ),
'name' => $welcome_name,
'address' => $welcome_text,
'roll_no' => 10
)
);
}
register_activation_hook(__FILE__, 'wp_activation_plugin_fun');
create table also by calling other function
function all_banner_setting_fun(){
wp_activation_plugin_fun();
}
function wp_activation_plugin_fun(){
global $wpdb;
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE wp_student (
id mediumint(9) NOT NULL AUTO_INCREMENT,
time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
name tinytext NOT NULL,
address text NOT NULL,
roll_no varchar(500) DEFAULT '' NOT NULL,
PRIMARY KEY (id)
) $charset_collate;";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
// add single demo data into wp_student table
$welcome_name = 'Mr. WordPress';
$welcome_text = 'Congratulations, you just completed the installation!';
$table_name = $wpdb->prefix . 'student';
$wpdb->insert(
$table_name,
array(
'time' => current_time( 'mysql' ),
'name' => $welcome_name,
'address' => $welcome_text,
'roll_no' => 10
)
);
}