I am trying to create a table on the Wordpress database as the plugin gets activated. My code is the following:
in the main plugin file:
register_activation_hook( __FILE__, 'sillyplugin_install');
in the activation.php
file:
function sillyplugin_install()
{
global $wpdb;
$table_name = $wpdb->prefix . 'sillyplugindata';
$charset_collate = $wpdb->get_charset_collate();
if ( $wpdb->get_var( "show tables like '$table_name'" ) != $table_name )
{
$sql = "create table $table_name (" .
"post_id bigint(20) unsigned not null," .
"comment_id bigint(20) unsigned not null," .
"silly_number int unsigned not null," .
"primary key(post_id, silly_number)," .
"foreign key(post_id) references wp_posts(ID) on delete cascade," .
"foreign key(comment_id) references wp_comments(comment_ID) on delete cascade" .
") $charset_collate;";
add_option( 'sillyplugindata_version', '1.0');
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
}
}
I can't figure out what goes wrong because everything seems to go fine except the table doesn't get created. All I managed to know is:
- the
register_activation_hook()
works properly and the callback function gets called; - if the table does not exist the function executes what's in the
if
statement as it should; - if I print the content of the
$sql
variable and try to execute the query manually on the MySQL client it works fine and it actually creates the table; - if I try to print the return value of
dbDelta()
I get returned an empty array - no error messages in the admin panel or debug/error log.
I am at loss here, why doesn't the table gets created?