vendredi 17 avril 2015

How to update the structure of custom table in WordPress?

I'm following this article on WordPress Codex. It says:



You will need to add the following lines to the end of your jal_install function, to check the version and upgrade if necessary:



So, finally the jal_install() function will like this:



function jal_install() {
global $wpdb;
global $jal_db_version;

$table_name = $wpdb->prefix . 'liveshoutbox';

$charset_collate = $wpdb->get_charset_collate();

$sql = "CREATE TABLE $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT,
time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
name tinytext NOT NULL,
text text NOT NULL,
url varchar(55) DEFAULT '' NOT NULL,
UNIQUE KEY id (id)
) $charset_collate;";

require_once ABSPATH . 'wp-admin/includes/upgrade.php';
dbDelta( $sql );

add_option( 'jal_db_version', $jal_db_version );

// ------ update table --------

global $wpdb;
$installed_ver = get_option( "jal_db_version" );

if ( $installed_ver != $jal_db_version ) {

$table_name = $wpdb->prefix . 'liveshoutbox';

$sql = "CREATE TABLE $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT,
time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
name tinytext NOT NULL,
text text NOT NULL,
url varchar(100) DEFAULT '' NOT NULL,
UNIQUE KEY id (id)
);";

require_once ABSPATH . 'wp-admin/includes/upgrade.php';
dbDelta( $sql );

update_option( "jal_db_version", $jal_db_version );
}
}


Obviously, most of the two parts of logic is duplicated. I think that the first part of codes is enough to update the structures, because the dbDelta() will check and update the table.


Do I misunderstand something in this article?


Aucun commentaire:

Enregistrer un commentaire