That’s not how you create tables with dbDelta
. dbDelta
expects an SQL statement as its argument, but the code in your question passes none. What’s more, the SQL is passed into wpdb->query
, and has no checks or sanitisation. A quick run of PHPCS would reveal warnings that no prepare call is used.
Instead, the official documentation at https://developer.wordpress.org/reference/functions/dbdelta/ has this example:
global $wpdb;
$table_name = $wpdb->prefix . 'dbdelta_test_001';
$wpdb_collate = $wpdb->collate;
$sql =
"CREATE TABLE {$table_name} (
id mediumint(8) unsigned NOT NULL auto_increment ,
first varchar(255) NULL,
PRIMARY KEY (id),
KEY first (first)
)
COLLATE {$wpdb_collate}";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta( $sql );
Note however, that dbDelta
has extremely specific formatting requirements. For example, there must be 2 spaces after PRIMARY KEY
. dbDelta
will also adjust existing tables to match the statement, and it will create the table if it doesn’t exist
Also keep in mind that in a lot of cases custom post types are easier and more performant. In this case, a CPT + taxonomy might be more performant in some circumstances due to the absence of indexes on the custom tables, and the loss of the internal WP_Cache system