I’m trying to create a custom plugin where I want create a table when the plugin gets activated. I have tried the following code but it is not creating the table in the database

function create_plugin_database_table() {
 global $wpdb;
 $table_name = $wpdb->prefix . 'sandbox';
 $sql = "CREATE TABLE $table_name (
 id mediumint(9) unsigned NOT NULL AUTO_INCREMENT,
 title varchar(50) NOT NULL,
 structure longtext NOT NULL,
 author longtext NOT NULL,
 PRIMARY KEY  (id)
 );";

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

register_activation_hook( __FILE__, 'create_plugin_database_table' );

3 s
3

You have to include wpadmin/upgrade-functions.php file to create a table
example

function create_plugin_database_table()
{
    global $table_prefix, $wpdb;

    $tblname="pin";
    $wp_track_table = $table_prefix . "$tblname ";

    #Check to see if the table exists already, if not, then create it

    if($wpdb->get_var( "show tables like '$wp_track_table'" ) != $wp_track_table) 
    {

        $sql = "CREATE TABLE `". $wp_track_table . "` ( ";
        $sql .= "  `id`  int(11)   NOT NULL auto_increment, ";
        $sql .= "  `pincode`  int(128)   NOT NULL, ";
        $sql .= "  PRIMARY KEY `order_id` (`id`) "; 
        $sql .= ") ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; ";
        require_once( ABSPATH . '/wp-admin/includes/upgrade.php' );
        dbDelta($sql);
    }
}

 register_activation_hook( __FILE__, 'create_plugin_database_table' );

Leave a Reply

Your email address will not be published. Required fields are marked *