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()};");
});
