Creare una tabella in un plugin personalizzato durante l'attivazione?
17 mar 2016, 10:55:13
Visualizzazioni: 49.6K
Voti: 9
Sto cercando di creare un plugin personalizzato dove voglio creare una tabella quando il plugin viene attivato. Ho provato il seguente codice ma non sta creando la tabella nel database
function create_plugin_database_table() {
global $wpdb;
$table_name = $wpdb->prefix . 'sandbox';
$sql = "CREATE TABLE $table_name (
id mediumint(9) unsigned NOT NULL AUTO_INCREMENT,
title varchar(50) NOT NULL,
structure longtext NOT NULL,
author longtext NOT NULL,
PRIMARY KEY (id)
);";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
}
register_activation_hook( __FILE__, 'create_plugin_database_table' );

Arun Kumaresh
193
Commenti
Tutte le risposte alla domanda
3
2
Devi includere il file wpadmin/upgrade-functions.php per creare una tabella esempio:
function create_plugin_database_table()
{
global $table_prefix, $wpdb;
$tblname = 'pin';
$wp_track_table = $table_prefix . "$tblname ";
# Controlla se la tabella esiste già, se no, la crea
if($wpdb->get_var( "show tables like '$wp_track_table'" ) != $wp_track_table)
{
$sql = "CREATE TABLE `". $wp_track_table . "` ( ";
$sql .= " `id` int(11) NOT NULL auto_increment, ";
$sql .= " `pincode` int(128) NOT NULL, ";
$sql .= " PRIMARY KEY `order_id` (`id`) ";
$sql .= ") ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; ";
require_once( ABSPATH . '/wp-admin/includes/upgrade.php' );
dbDelta($sql);
}
}
register_activation_hook( __FILE__, 'create_plugin_database_table' );

dipika
204
17 mar 2016 12:10:15
0
Questo codice funziona per me:
function installer(){
include('installer.php');
}
register_activation_hook(__file__, 'installer');
Poi installer.php:
global $wpdb;
$table_name = $wpdb->prefix . "my_products";
$my_products_db_version = '1.0.0';
$charset_collate = $wpdb->get_charset_collate();
if ( $wpdb->get_var("SHOW TABLES LIKE '{$table_name}'") != $table_name ) {
$sql = "CREATE TABLE $table_name (
ID mediumint(9) NOT NULL AUTO_INCREMENT,
`product-model` text NOT NULL,
`product-name` text NOT NULL,
`product-description` int(9) NOT NULL,
PRIMARY KEY (ID)
) $charset_collate;";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
add_option('my_db_version', $my_products_db_version);
}

Jismon Thomas
211
15 mar 2018 00:20:47
2
function astro_plugin_table_install() {
global $wpdb;
global $charset_collate;
$table_name = $wpdb->prefix . 'pin';
$sql = "CREATE TABLE IF NOT EXISTS $table_name (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`pincode` bigint(128) DEFAULT NOT NULL,
PRIMARY KEY (`id`)
)$charset_collate;";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
}
register_activation_hook(__FILE__,'astro_plugin_table_install');

Pankaj Kumar
11
28 dic 2017 16:02:39
Domande correlate
2
risposte
2
risposte