Creating Custom Database Tables in WordPress with dbDelta

While WordPress relies heavily on standard tables like wp_posts, wp_usermeta, and wp_options, complex applications often require custom database tables to store specialized data efficiently—such as custom logs, user submissions, telemetry, or transaction records.

Directly running raw SQL CREATE TABLE queries can cause issues during theme or plugin activations. Instead, WordPress provides the dbDelta() function, which safely creates or updates database tables by comparing your schema against the existing database structure.

In this tutorial, we will walk through creating a custom database table using dbDelta, performing secure queries with $wpdb, and handling proper cleanup upon uninstallation.

1. Defining and Creating the Custom Table with dbDelta

To create a table correctly, we hook into plugin activation (or theme setup) and use dbDelta().

Important Note: dbDelta has strict formatting rules: you must place each column on its own line, include two spaces after the PRIMARY KEY definition, and specify the character set.

Add the following code to your custom plugin or theme’s initialization file:

				
					if (!defined('ABSPATH')) {
    exit;
}

function wg_create_custom_database_table() {
    global $wpdb;

    // Define table name with correct WordPress prefix
    $table_name = $wpdb->prefix . 'wg_submissions';

    // Get database collation charset
    $charset_collate = $wpdb->get_charset_collate();

    // SQL query following dbDelta strict formatting rules
    $sql = "CREATE TABLE $table_name (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
        name varchar(100) NOT NULL,
        email varchar(100) NOT NULL,
        message text NOT NULL,
        PRIMARY KEY  (id)
    ) $charset_collate;";

    // Include upgrade.php to make dbDelta available
    require_once ABSPATH . 'wp-admin/includes/upgrade.php';
    dbDelta($sql);
}

// Hook into activation (use register_activation_hook for plugins)
register_activation_hook(__FILE__, 'wg_create_custom_database_table');
				
			

2. Inserting and Querying Data Safely Using $wpdb

Once your table is created, you can interact with it using WordPress’s global database abstraction class, $wpdb. Always use $wpdb->prepare() to prevent SQL injection vulnerabilities when dealing with user input.

Here is how to insert a new record:

				
					function wg_insert_submission_data($name, $email, $message) {
    global $wpdb;
    $table_name = $wpdb->prefix . 'wg_submissions';

    $inserted = $wpdb->insert(
        $table_name,
        [
            'time'    => current_time('mysql'),
            'name'    => sanitize_text_field($name),
            'email'   => sanitize_email($email),
            'message' => sanitize_textarea_field($message),
        ],
        ['%s', '%s', '%s', '%s'] // Data formats
    );

    return $inserted ? $wpdb->insert_id : false;
}
				
			

And how to retrieve records securely:

				
					function wg_get_recent_submissions($limit = 10) {
    global $wpdb;
    $table_name = $wpdb->prefix . 'wg_submissions';

    // Use prepare for safe querying with variables
    $query = $wpdb->prepare(
        "SELECT * FROM $table_name ORDER BY time DESC LIMIT %d",
        $limit
    );

    return $wpdb->get_results($query);
}
				
			

3. Best Practices for Table Cleanup

If your plugin or theme is uninstalled, it is a good practice to clean up your custom tables so you don’t leave orphaned data behind. However, be cautious with this on production sites:

				
					function wg_drop_custom_database_table() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'wg_submissions';
    
    // Drop table safely
    $wpdb->query("DROP TABLE IF EXISTS $table_name");
}

// Use register_uninstall_hook for plugins
register_uninstall_hook(__FILE__, 'wg_drop_custom_database_table');
				
			

Using dbDelta() combined with $wpdb allows you to scale your WordPress projects beyond standard posts and meta tables. It keeps your database structured, performant, and secure.

Be sure to check out our previous tutorials on WordPress development:
Creating Custom Dashboard Widgets in WordPress
How to Create Custom Options Pages in WordPress Admin Without Plugins
How to Handle File Uploads in WordPress via AJAX & Fetch API

Need help with your project? We will be happy to help with your project. Feel free to contact us. Just reach out and we will reply soon.

Comments

No comments yet

Share Your Thoughts

Join the conversation!

Scroll to Top

Share Your Thoughts

Thank you for your comment!

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

Pro

Thank you for reaching out! We’ll be in touch within 24 hours to discuss your project

Standard

Thank you for reaching out! We’ll be in touch within 24 hours to discuss your project

Basic

Thank you for reaching out! We’ll be in touch within 24 hours to discuss your project