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
function plugin_name_activation() {
	require_once( ABSPATH . '/wp-admin/includes/upgrade.php' );
	global $wpdb;
	$db_table_name = $wpdb->prefix . 'table_name';
	if( $wpdb->get_var( "SHOW TABLES LIKE '$db_table_name'" ) != $db_table_name ) {
		if ( ! empty( $wpdb->charset ) )
			$charset_collate = "DEFAULT CHARACTER SET $wpdb->charset";
		if ( ! empty( $wpdb->collate ) )
			$charset_collate .= " COLLATE $wpdb->collate";

		$sql = "CREATE TABLE " . $db_table_name . " (
			`id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
			`type` varchar(100) NOT NULL DEFAULT '',
			`extra` longtext NOT NULL,
			`date_time` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
			PRIMARY KEY (`id`)
		) $charset_collate;";
		dbDelta( $sql );
	}
}
register_activation_hook(__FILE__, 'plugin_name_activation');
?>

Creating Tables with WordPress Plugins.

4 thoughts on “WordPress create table on plugin activation”

Leave a Reply to Anwer Cancel reply