The dbdelta_queries WordPress PHP filter allows you to modify the array of SQL queries used by the dbDelta
function, which updates a WordPress database schema.
Usage
add_filter('dbdelta_queries', 'your_custom_function'); function your_custom_function($queries) { // your custom code here return $queries; }
Parameters
$queries
(string[]): An array ofdbDelta
SQL queries.
More information
See WordPress Developer Resources: dbdelta_queries
Examples
Adding a new table to the database
Add a new custom table called ‘my_custom_table’ to the WordPress database.
add_filter('dbdelta_queries', 'add_my_custom_table'); function add_my_custom_table($queries) { $queries[] = "CREATE TABLE my_custom_table ( id bigint(20) unsigned NOT NULL AUTO_INCREMENT, name varchar(255) NOT NULL, PRIMARY KEY (id) )"; return $queries; }
Modifying an existing table
Add a new column ’email’ to the existing ‘my_custom_table’.
add_filter('dbdelta_queries', 'modify_my_custom_table'); function modify_my_custom_table($queries) { $queries[] = "ALTER TABLE my_custom_table ADD email varchar(255) NOT NULL"; return $queries; }
Removing a table from the database
Remove ‘my_custom_table’ from the WordPress database.
add_filter('dbdelta_queries', 'remove_my_custom_table'); function remove_my_custom_table($queries) { $queries[] = "DROP TABLE IF EXISTS my_custom_table"; return $queries; }
Adding an index to a table
Add a unique index for the ’email’ column in ‘my_custom_table’.
add_filter('dbdelta_queries', 'add_index_to_my_custom_table'); function add_index_to_my_custom_table($queries) { $queries[] = "ALTER TABLE my_custom_table ADD UNIQUE (email)"; return $queries; }
Modifying multiple tables
Add a new column ‘created_at’ to both ‘my_custom_table’ and ‘another_custom_table’.
add_filter('dbdelta_queries', 'modify_multiple_tables'); function modify_multiple_tables($queries) { $queries[] = "ALTER TABLE my_custom_table ADD created_at datetime NOT NULL"; $queries[] = "ALTER TABLE another_custom_table ADD created_at datetime NOT NULL"; return $queries; }