Function Name: dbDelta
If you’re creating a WordPress plugin or theme that interacts with a database, you’ll likely need to create and modify tables. One of the most useful functions for this is dbDelta(), which is used to manage database schema changes by comparing the current table structure to the desired structure.
When you run dbDelta(), it checks whether the table already exists. If it doesn’t, it creates the table using the specified SQL code. If the table does exist, it checks the columns and indexes to see whether any changes need to be made. If so, it modifies the table accordingly.
Here’s an example usage code for creating a simple table using dbDelta():
function myplugin_install() {
global $wpdb;
$charset_collate = $wpdb->get_charset_collate();
$table_name = $wpdb->prefix . 'myplugin_table';
$sql = "CREATE TABLE $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT,
name tinytext NOT NULL,
email varchar(100) NOT NULL,
PRIMARY KEY (id)
) $charset_collate;";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
}
register_activation_hook( __FILE__, 'myplugin_install' );
In this example, we’re creating a table called "myplugin_table" with three fields: "id", "name", and "email". The "id" field is set to auto-increment and is the primary key for the table. The "name" field is a tinytext field and the "email" field is a varchar field with a length of 100 characters.
Overall, the dbDelta() function is an essential tool for managing database schema changes in WordPress plugins and themes.