Create a Custom Database Table in a WordPress Plugin with dbDelta

Create a custom database table in a WordPress plugin with dbDelta

wp_postmeta stores any key-value data, but for high-volume or relational plugin data (logs, statistics, bookings) it becomes a bottleneck: every value is a LONGTEXT in one huge table, and filtering by several values means several joins. A custom table gives you your own columns with proper types and indexes for your queries.

Problem: Plugin data stored in wp_postmeta makes the queries slow and the table huge for the whole site.

Solution: Create the table on plugin activation with dbDelta(), keep the schema version in an option to upgrade the table later, and query it with $wpdb->prepare().

Create the table

<?php
const MY_PLUGIN_DB_VERSION = '1.0';

register_activation_hook( __FILE__, 'my_plugin_create_table' );

function my_plugin_create_table() {
    global $wpdb;

    $table   = $wpdb->prefix . 'my_custom_data';
    $charset = $wpdb->get_charset_collate();

    $sql = "CREATE TABLE $table (
  id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  user_id bigint(20) unsigned NOT NULL,
  action_type varchar(50) NOT NULL,
  details longtext NOT NULL,
  created_at datetime NOT NULL,
  PRIMARY KEY  (id),
  KEY user_id (user_id),
  KEY action_created (action_type, created_at)
) $charset;";

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

    update_option( 'my_plugin_db_version', MY_PLUGIN_DB_VERSION );
}

$wpdb->prefix gives the table prefix of the current site (in a multisite every site has its own), and get_charset_collate() the character set and collation of the WordPress database.

dbDelta() compares the statement with the existing table and adds what is missing (columns, indexes), so the same function also upgrades the table. It is very strict about the format:

  • every column and every key on its own line;
  • two spaces between PRIMARY KEY and the column list;
  • KEY instead of INDEX, and every key has a name;
  • no backticks around names, lowercase types.

If the format is wrong, dbDelta() does not report an error, it just misses changes or tries to add the same index again.

Upgrade on plugin update

The activation hook does not run when a plugin is updated. To apply schema changes from a new version, compare the stored version on load:

<?php
add_action( 'plugins_loaded', function () {
    if ( get_option( 'my_plugin_db_version' ) !== MY_PLUGIN_DB_VERSION ) {
        my_plugin_create_table();
    }
} );

dbDelta() never drops columns: renames and removals need your own ALTER TABLE in this upgrade step.

Read and write

<?php
function my_plugin_log_action( $user_id, $action_type, $details ) {
    global $wpdb;

    return $wpdb->insert(
        $wpdb->prefix . 'my_custom_data',
        array(
            'user_id'     => $user_id,
            'action_type' => $action_type,
            'details'     => wp_json_encode( $details ),
            'created_at'  => current_time( 'mysql', true ), // UTC
        ),
        array( '%d', '%s', '%s', '%s' )
    );
}

function my_plugin_get_user_actions( $user_id, $limit = 20 ) {
    global $wpdb;
    $table = $wpdb->prefix . 'my_custom_data';

    return $wpdb->get_results( $wpdb->prepare(
        "SELECT id, action_type, details, created_at FROM $table WHERE user_id = %d ORDER BY created_at DESC LIMIT %d",
        $user_id,
        $limit
    ) );
}

$wpdb->insert() escapes the values itself according to the formats. The table name is not user input, so it can go into the SQL string directly; everything else goes through placeholders. To check that your indexes are used, see EXPLAIN and indexes.

NOTE: Decide what happens to the table when the plugin is deleted: drop it in uninstall.php ($wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}my_custom_data" )) and delete the version option. Not on deactivation: users deactivate plugins temporarily and do not expect to lose data.