Skip to content

Instantly share code, notes, and snippets.

@danielpataki
Last active February 22, 2021 16:21
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save danielpataki/b45306318d19af77e24f to your computer and use it in GitHub Desktop.
Save danielpataki/b45306318d19af77e24f to your computer and use it in GitHub Desktop.
WordPress Custom Database Tables
register_activation_hook( __FILE__, 'my_plugin_create_db' );
function my_plugin_create_db() {
// Create DB Here
}
function my_plugin_create_db() {
global $wpdb;
$charset_collate = $wpdb->get_charset_collate();
$table_name = $wpdb->prefix . 'my_analysis';
$sql = "CREATE TABLE $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT,
time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
views smallint(5) NOT NULL,
clicks smallint(5) NOT NULL,
UNIQUE KEY id (id)
) $charset_collate;";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
}
function my_plugin_create_db() {
global $wpdb;
$version = get_option( 'my_plugin_version', '1.0' );
$charset_collate = $wpdb->get_charset_collate();
$table_name = $wpdb->prefix . 'my_analysis';
$sql = "CREATE TABLE $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT,
time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
views smallint(5) NOT NULL,
clicks smallint(5) NOT NULL,
UNIQUE KEY id (id)
) $charset_collate;";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
if ( version_compare( $version, '2.0' ) < 0 ) {
$sql = "CREATE TABLE $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT,
time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
views smallint(5) NOT NULL,
clicks smallint(5) NOT NULL,
blog_id smallint(5) NOT NULL,
UNIQUE KEY id (id)
) $charset_collate;";
dbDelta( $sql );
update_option( 'my_plugin_version', '2.0' );
}
}
function my_plugin_create_db() {
global $wpdb;
$version = get_option( 'my_plugin_version', '1.0' );
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment