Sunday, February 17, 2019

Wordpress create table on Plugin activation if not exists

<?php
global $wpdb;
$table1 = $wpdb->prefix . "my_table";

if($wpdb->get_var( "show tables like '$table1'" ) != $table1) {
    $sql = "CREATE TABLE `". $table1 . "` ( ";
    $sql .= "  `post_id` BIGINT NULL, ";
    $sql .= "  `field1` VARCHAR(250) NULL, ";
    $sql .= "  `field2` VARCHAR(250) NULL, ";
    $sql .= "  INDEX `index_by_post_id` (`post_id`) ";
    $sql .= ") ENGINE=MyISAM DEFAULT CHARSET=latin1 ; ";
    require_once( ABSPATH . '/wp-admin/includes/upgrade.php' );
    dbDelta($sql);
}

No comments:

Post a Comment