stackwordpress,beginner

How To Create table with plugin creating and active in WordPress

you will almost certainly find database table that you need to store some information in the WordPress database.

Create Database Tables
The first step in making your plugin create database tables automatically is to create a custom PHP function within your plugins that adds a table or tables to the WordPress MySQL database.

So, it is recommended that you following the steps below to create a plugin automatically create its  tables:

step 1. Write a function file  describe all create details like name author etc for plugin.

step 2. Write a function table name  for plugin.

function custom_install () {
   global $wpdb;

   $table_name = $wpdb->prefix . "custom_table_name"; 
}

step 3. Write a detail for database sql table field like below detail.

global $wpdb;

$charset_collate = $wpdb->get_charset_collate();

$sql = "CREATE TABLE $table_name (
  id int(9) NOT NULL AUTO_INCREMENT,
  time datetime DEFAULT  NOT NULL,
  name varchare(55) NOT NULL,
  email varchare(55) NOT NULL,
  url varchar(55) DEFAULT '' NOT NULL,
  PRIMARY KEY  (id)
) $charset_collate;";

require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );

Step 4. following hooks for acitvation and de-activiation plugin following it.

register_activation_hook( __FILE__, ‘custom_install’ );
register_deactivation_hook( __FILE__, 'custom_remove_database' );

Step 5. delete table when de-activete plugin following function.

// Delete table when deactivate
function custom_remove_database() {
     global $wpdb;
     $table_name = "custom_table_name";
     $sql = "DROP TABLE IF EXISTS $table_name;";
     $wpdb->query($sql);
    
}    
register_deactivation_hook( __FILE__, 'custom_remove_database' );

this function deletes tables when the plugin is de-activated

Social Share

1 thought on “How To Create table with plugin creating and active in WordPress”

Leave a Comment