The dbdelta_create_queries WordPress PHP filter allows you to modify the SQL queries for creating tables and/or databases using the dbDelta function.
Usage
add_filter('dbdelta_create_queries', 'your_custom_function_name');
function your_custom_function_name($cqueries) {
// your custom code here
return $cqueries;
}
Parameters
- $cqueries (string[]): An array of dbDelta create SQL queries.
More information
See WordPress Developer Resources: dbdelta_create_queries
Examples
Adding a prefix to table names
To add a custom prefix to all table names in the queries:
add_filter('dbdelta_create_queries', 'add_custom_table_prefix');
function add_custom_table_prefix($cqueries) {
$prefix = 'custom_';
foreach ($cqueries as &$query) {
$query = preg_replace('/CREATE TABLE `?(\w+)/', 'CREATE TABLE `' . $prefix . '$1', $query);
}
return $cqueries;
}
Converting table storage engine to InnoDB
To change the storage engine for all tables to InnoDB:
add_filter('dbdelta_create_queries', 'convert_to_innodb');
function convert_to_innodb($cqueries) {
foreach ($cqueries as &$query) {
$query = str_ireplace('ENGINE=MyISAM', 'ENGINE=InnoDB', $query);
}
return $cqueries;
}
Adding a column to a specific table
To add a new column to a specific table in the queries:
add_filter('dbdelta_create_queries', 'add_column_to_table');
function add_column_to_table($cqueries) {
$table_name = 'your_table_name';
$column = "new_column_name INT(11) NOT NULL";
foreach ($cqueries as &$query) {
if (strpos($query, $table_name) !== false) {
$query = str_replace(') ENGINE', ", $column) ENGINE", $query);
}
}
return $cqueries;
}
Remove a specific table
To remove a specific table from the queries:
add_filter('dbdelta_create_queries', 'remove_specific_table');
function remove_specific_table($cqueries) {
$table_name = 'your_table_name';
foreach ($cqueries as $key => $query) {
if (strpos($query, $table_name) !== false) {
unset($cqueries[$key]);
}
}
return $cqueries;
}
Replacing table charset
To replace the charset for all tables in the queries:
add_filter('dbdelta_create_queries', 'replace_table_charset');
function replace_table_charset($cqueries) {
$new_charset = 'utf8mb4';
foreach ($cqueries as &$query) {
$query = preg_replace('/CHARSET=\w+/', 'CHARSET=' . $new_charset, $query);
}
return $cqueries;
}