Creating a custom table for the WordPress CMS may be necessary in the following cases:
- When developing your own plugin
- When creating your own theme (e.g., for real estate, car sales or rental, etc.)
In my projects, to create tables or import data into the database, I use the WP function `dbDelta` within the `register_activation_hook()`. Example code:
register_activation_hook(__FILE__, function()
{
global $wpdb;
require_once(ABSPATH.'wp-admin/includes/upgrade.php');
dbDelta("CREATE TABLE IF NOT EXISTS `{$wpdb -> prefix}my_table` (
`id` INT(11) UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT,
`title` VARCHAR(255) NOT NULL,
`date_create` INT(10) UNSIGNED NOT NULL
) {$wpdb -> get_charset_collate()};");
});The code above must be placed in the main file of your plugin. Otherwise, it won’t work (at least it didn’t for me).
Everything here is quite straightforward:
- Just in case, we include the file with the necessary functions — `upgrade.php`
- We use the global variable `$wpdb` to get the current DB prefix and charset using `$wpdb->get_charset_collate()`
The second way to create tables is based on the `$wpdb->query()` function and looks like this:
register_activation_hook(__FILE__, function()
{
global $wpdb;
$wpdb -> query("CREATE TABLE IF NOT EXISTS `{$wpdb -> prefix}my_table` (
`id` INT(11) UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT,
`title` VARCHAR(255) NOT NULL,
`date_create` INT(10) UNSIGNED NOT NULL
) {$wpdb -> get_charset_collate()};");
});Strangely enough, I learned about this second method later. Although I’m quite sure I tried it earlier when I was just starting out with WordPress — and it didn’t work for me back then.
But now it works — a miracle 🙂
Note: All examples above work only for plugins. They won’t work during theme initialization.
