WordPress create table on plugin activation

Table is created if it is not exist and updates if it exist. Update includes create field or change field type. Update does not include field deleting.

<?php
register_activation_hook(__FILE__, 'plugin_install');
function plugin_install() {
	require_once( ABSPATH . '/wp-admin/includes/upgrade.php' );
	global $wpdb;
	$table = $wpdb->prefix . 'teable_name';
	if( $wpdb->get_var( "SHOW TABLES LIKE '$table'" ) != $table ) {
		if ( ! empty( $wpdb->charset ) )
			$charset_collate = "DEFAULT CHARACTER SET $wpdb->charset";
		if ( ! empty( $wpdb->collate ) )
			$charset_collate .= " COLLATE $wpdb->collate";
 
		$sql = "CREATE TABLE " . $table . " (
			`post_id` bigint(20) UNSIGNED NOT NULL DEFAULT '0',
			`date_time` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
			`desc` varchar(100) NOT NULL DEFAULT '',
			UNIQUE KEY (post_id)
		) $charset_collate;";
		dbDelta( $sql );
	}
}
?>

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">