Come creare una tabella nel Database di WordPress

Piccolo snippet di codice che ti permette di creare una nuova tabella all’interno del DB di WordPress. Utile nel caso tu debba salvare dati aggiuntivi generati dal tuo plugin.

Questa funzione, solitamente, viene richiamata all’attivazione del plugin, tramite register_activation_hook()

function create_table( $table_name ) {
 global $wpdb;
 $charset_collate = $wpdb->get_charset_collate();
 // RICORDATI GLI APICI SINGOLI SUL NOME DELLA TABELLA
 if ( $wpdb->get_var( "SHOW TABLES LIKE '$table_name'" ) != $table_name ) {
$sql = "CREATE TABLE $table_name (
  id bigint(20) NOT NULL AUTO_INCREMENT,
  product_id bigint(20) DEFAULT 0 NOT NULL,
  parent_product_id bigint(20) DEFAULT 0 NOT NULL,
  date_created datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
  date_modified datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
  tmstamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP  ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY  (id),
  UNIQUE (product_id)
) $charset_collate;";

require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
 } else {
 //tabella già presente
 }
}