WordPress Databases – Using dbDelta

, , ,

There are plenty of times you need to create extra database tables for storing data within WordPress.  Sometimes a scope of an addon has changed and you need to modify the table.  Using dbDelta within WordPress can allow you to modify the table without having to use phpMyAdmin or do anything to the stored data.  https://codex.wordpress.org/Creating_Tables_with_Plugins talks about how to create tables with plugins. Here is what I use for a plugin and also to uninstall on deactivation.

<?php

 // Exit if accessed directly
 if ( ! defined( 'ABSPATH' ) ) {
  exit;
 }
 
 function some_plugin_db_sync() {
 	global $wpdb;
 	require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
 	$charset_collate = $wpdb->get_charset_collate();
 	$someSql = "CREATE TABLE ". $wpdb->prefix . "some_plugin_tablename" ." (
 					id INT(11) NOT NULL AUTO_INCREMENT,
 					some_number INT(11) NOT NULL,
 					other_number INT(11) NOT NULL,
 					info_timestamp timestamp NOT NULL default NOW(),
 					PRIMARY KEY (id)
 					) $charset_collate;";			
 	dbDelta($someSql );
 	// If you need to implement more tables you can do so by repeating the above sql and dbDelta call. 
 }
 
 function some_plugin_db_removal() {
     global $wpdb;
     $wpdb->query( "DROP TABLE IF EXISTS " . $wpdb->prefix . "some_plugin_tablename"  );
 }

 


 

Skills

Posted on

April 27, 2017

Submit a Comment

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