Using WordPress ‘maybe_create_table()’ PHP function

The maybe_create_table() WordPress PHP function checks if a table exists in the database and creates it if not already present.

Usage

require_once ABSPATH . 'wp-admin/includes/upgrade.php';
global $wpdb;
$table_name = 'custom_table';
$create_ddl = 'CREATE TABLE ' . $table_name . ' (...);';
maybe_create_table($wpdb->prefix . $table_name, $create_ddl);

Parameters

  • $table_name (string) – Required. The name of the database table.
  • $create_ddl (string) – Required. The SQL statement to create the table.

More information

See WordPress Developer Resources: maybe_create_table

Important: Before calling this function, you must manually include ‘upgrade.php’ to avoid the white screen of death:

require_once(ABSPATH . 'wp-admin/includes/upgrade.php');

Examples

Create a simple table for storing user preferences

This code creates a table named ‘user_preferences’ with three columns: user_id, preference_key, and preference_value.

require_once ABSPATH . 'wp-admin/includes/upgrade.php';
global $wpdb;
$table_name = 'user_preferences';
$create_ddl = "CREATE TABLE " . $table_name . " (
    user_id bigint(20) unsigned NOT NULL,
    preference_key varchar(255) NOT NULL,
    preference_value varchar(255) NOT NULL,
    PRIMARY KEY (user_id, preference_key)
);";
maybe_create_table($wpdb->prefix . $table_name, $create_ddl);

Create a table for storing custom post metadata

This code creates a table named ‘custom_post_meta’ with four columns: meta_id, post_id, meta_key, and meta_value.

require_once ABSPATH . 'wp-admin/includes/upgrade.php';
global $wpdb;
$table_name = 'custom_post_meta';
$create_ddl = "CREATE TABLE " . $table_name . " (
    meta_id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
    post_id bigint(20) unsigned NOT NULL,
    meta_key varchar(255) DEFAULT NULL,
    meta_value longtext,
    PRIMARY KEY (meta_id),
    KEY post_id (post_id),
    KEY meta_key (meta_key)
);";
maybe_create_table($wpdb->prefix . $table_name, $create_ddl);

Create a table for storing product inventory

This code creates a table named ‘product_inventory’ with four columns: product_id, location_id, quantity, and last_updated.

require_once ABSPATH . 'wp-admin/includes/upgrade.php';
global $wpdb;
$table_name = 'product_inventory';
$create_ddl = "CREATE TABLE " . $table_name . " (
    product_id bigint(20) unsigned NOT NULL,
    location_id bigint(20) unsigned NOT NULL,
    quantity int(11) NOT NULL,
    last_updated datetime NOT NULL,
    PRIMARY KEY (product_id, location_id)
);";
maybe_create_table($wpdb->prefix . $table_name, $create_ddl);

Create a table for storing user achievements

This code creates a table named ‘user_achievements’ with three columns: achievement_id, user_id, and date_achieved.

require_once ABSPATH . 'wp-admin/includes/upgrade.php';
global $wpdb;
$table_name = 'user_achievements';
$create_ddl = "CREATE TABLE " . $table_name . " (
    achievement_id bigint(20) unsigned NOT NULL,
    user