How to Create a Table in WordPress Database

How to Create a Table in WordPress Database

Creating a custom table for the WordPress CMS may be necessary in the following cases:

  1. When developing your own plugin
  2. 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:

  1. Just in case, we include the file with the necessary functions — `upgrade.php`
  2. 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.

Posts on similar topics

Are you having problems with your WordPress site? Do you need additional functionality? A custom plugin or a new page?
Then write to me via the feedback form, and I will try to help you.

Write a comment

Your email address will not be published. Required fields are marked *