DocsStation
WordPress Plugin Development

WordPress Custom Database Tables

By csestudy247 Updated November 23, 2026 27 min read
27 min read

Learning Objectives

By mastering this chapter, developers will be able to:

  • Evaluate when a plugin requires custom MySQL tables versus leveraging native WordPress options or metadata tables.
  • Access and utilize the global $wpdb database class to retrieve environment-specific table prefixes and character collations dynamically.
  • Write schema-compatible SQL CREATE TABLE queries conforming strictly to WordPress dbDelta() syntax formatting standards.
  • Safely execute dbDelta() by importing wp-admin/includes/upgrade.php inside custom database initialization functions.
  • Register plugin activation routines (register_activation_hook) correctly within the root plugin file to execute database creation logic.
  • Implement database version constants (MSR_DB_VERSION) and track schema states in wp_options.
  • Architect automated database migration and upgrade mechanisms hooked into plugins_loaded to update schema structures seamlessly during plugin updates.

Key Concepts & Prerequisites

  • Key Concepts: Custom Database Tables, $wpdb Abstraction Class, Dynamic Table Prefixes ($wpdb->prefix), Character Set Collation ($wpdb->get_charset_collate()), dbDelta() Schema Engine, Plugin Activation Hook (register_activation_hook), Database Schema Versioning, Automated Migrations (plugins_loaded).
  • Prerequisites: Intermediate PHP syntax, basic MySQL relational database concepts (CREATE TABLE, primary keys, indexes, data types), familiarity with WordPress action hooks (init, plugins_loaded) covered in Lecture 06, modular directory layouts from Lecture 05, and Options API usage from Lectures 09 & 10.

Concept Explanation & Database Architecture

When & Why Custom Database Tables Are Needed

WordPress comes pre-packaged with 12 standard database tables (such as wp_posts, wp_postmeta, wp_options, wp_users, wp_usermeta, wp_comments, etc.). For basic plugin configurations, developers store simple key-value settings in wp_options using the Options API or attach key-value pairs to posts using wp_postmeta.

However, relying exclusively on wp_options or wp_postmeta for high-volume or transactional data creates significant performance bottlenecks and database bloat.

WordPress Data Storage Options
├── Options API (wp_options) ──> Small, global plugin settings & key-value options
├── Metadata API (wp_postmeta) ─> Unstructured key-value attributes attached to posts
└── Custom MySQL Tables ────────> Structured, high-volume transactional data (Reactions, Analytics, Logs)

Why Custom Tables Are Needed:

  • Performance at Scale: Storing thousands of individual user interactions (such as post reactions, analytics clicks, or audit logs) inside wp_postmeta results in bloated database tables and slow, un-indexed SQL queries. Custom tables allow optimized column types and custom indexes.
  • Data Integrity & Relational Structure: Custom tables enforce strict data types (e.g., BIGINT, VARCHAR, DATETIME), default values, primary keys, and multi-column indexes that wp_postmeta cannot enforce.
  • Separation of Concerns: Storing plugin-specific transactional data in separate tables keeps core WordPress tables clean, enabling lightweight backups, easy data exports, and clean plugin uninstallation.

The $wpdb Global Database Abstraction Class

Directly calling PHP mysqli_query() or PDO inside WordPress is strictly forbidden. WordPress provides a global database abstraction layer via the $wpdb class instance, which handles SQL escaping, connection management, and database prefix resolution.

global $wpdb;

Key $wpdb Properties & Methods:

  • $wpdb->prefix: Contains the dynamic database table prefix set during WordPress installation (e.g., wp_ or wp_customprefix_). Developers must concatenate $wpdb->prefix . 'my_table_name' so the plugin works across any WordPress site regardless of custom prefix settings.
  • $wpdb->get_charset_collate(): Returns the database character set and collation string defined in wp-config.php (e.g., DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci). Appending this string to CREATE TABLE queries ensures international language support and database compatibility.

The dbDelta() Schema Engine & Formatting Rules

To create or modify database tables safely, WordPress provides a specialized function named dbDelta(). Unlike raw SQL CREATE TABLE statements, dbDelta() examines the current database structure, compares it against the target SQL declaration, and intelligently applies missing tables or columns without dropping existing data.

Mandatory Formatting Rules for dbDelta():

The dbDelta() parser is extremely sensitive to SQL syntax formatting. Violating any of these rules causes dbDelta() to silently fail or execute incorrectly:

  1. Separate Line Per Field: Every column declaration must reside on its own line in the SQL string.
  2. Two Spaces After PRIMARY KEY: The phrase PRIMARY KEY must be followed by exactly two spaces before defining the key column in parentheses: PRIMARY KEY (id).
  3. Keyword KEY for Indexes: You must use the keyword KEY (not INDEX) when declaring indexes, followed by a key name and two spaces: KEY post_id (post_id).
  4. All Caps Keywords: Standard SQL keywords (CREATE TABLE, PRIMARY KEY, NOT NULL, DEFAULT, AUTO_INCREMENT) must be written in uppercase.
  5. Include Data Types & Lengths: Every field must specify an explicit data type with length limits where applicable (e.g., varchar(100)).
CREATE TABLE wp_msr_reactions (
    id bigint(20) NOT NULL AUTO_INCREMENT,
    post_id bigint(20) NOT NULL,
    user_id bigint(20) NOT NULL,
    reaction_type varchar(50) NOT NULL,
    reaction_count int(11) DEFAULT 0 NOT NULL,
    created_at datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
    updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL,
    PRIMARY KEY  (id),
    KEY post_id  (post_id),
    KEY user_id  (user_id)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

Activation Hook Context & Subdirectory Architecture

A common trap encountered during plugin development is calling register_activation_hook() inside a included file located in a subdirectory (e.g., inc/db.php).

When register_activation_hook( __FILE__, 'callback' ) is invoked inside inc/db.php, PHP resolves __FILE__ to the path /wp-content/plugins/msr-plugin/inc/db.php rather than the main plugin file /wp-content/plugins/msr-plugin/msr-plugin.php. Because WordPress checks activation hooks against main plugin file paths, the activation hook fails to trigger.

The Golden Rule of Activation Hooks:

  • register_activation_hook() MUST always be called inside the main root plugin file (msr-plugin.php), passing the main file’s path.
  • The table creation function logic itself can reside inside inc/db.php, bootstrapped and called by the main activation hook callback.

Database Versioning & Automated Schema Migrations

When a plugin releases an update that adds new database columns or creates additional tables, existing users who update the plugin will not trigger register_activation_hook() because activation hooks run only when a user manually deactivates and reactivates a plugin.

To update database tables seamlessly during automated plugin updates:

  1. Define a global constant for the plugin’s target database schema version (e.g., define( 'MSR_DB_VERSION', '1.0.1' )).
  2. Store the installed schema version in the wp_options database table via add_option( 'msr_db_version', '1.0.0' ).
  3. Hook an upgrade checker function to plugins_loaded.
  4. Compare get_option('msr_db_version') against MSR_DB_VERSION. If the stored version is less than the current constant, re-run dbDelta() with the updated schema query and update the stored version in wp_options.

Deep-Dive Code Explanation

Snippet: Main Plugin File Hook Registration

<?php
/**
 * Plugin Name: MSR Plugin
 * Description: Demonstrates custom database table creation and schema migrations.
 * Version: 1.0.0
 * Author: WP Academy
 */

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

// Define Plugin Path & Version Constants
define( 'MSR_PLUGIN_DIR_PATH', plugin_dir_path( __FILE__ ) );
define( 'MSR_PLUGIN_DIR_URL', plugin_dir_url( __FILE__ ) );
define( 'MSR_PLUGIN_VERSION', '1.0.0' );
define( 'MSR_DB_VERSION', '1.0.0' );

// Include Database Operations Handler
require_once MSR_PLUGIN_DIR_PATH . 'inc/db.php';

// Register Activation Hook in Root File
register_activation_hook( __FILE__, 'msr_create_db_tables' );

// Check for Database Schema Upgrades on Plugins Loaded
add_action( 'plugins_loaded', 'msr_update_db_check' );
Line-by-Line Detailed Explanation:
  1. define( 'MSR_DB_VERSION', '1.0.0' );: Declares a version string tracking the current database schema state.
  2. require_once MSR_PLUGIN_DIR_PATH . 'inc/db.php';: Includes the database setup and migration functions.
  3. register_activation_hook( __FILE__, 'msr_create_db_tables' );: Attaches the msr_create_db_tables function to plugin activation. Passing __FILE__ from msr-plugin.php ensures WordPress registers the hook correctly.
  4. add_action( 'plugins_loaded', 'msr_update_db_check' );: Hooks an automated version check into plugins_loaded so schema updates run automatically when plugin files are updated without requiring manual re-activation.

Snippet: Custom Database Table Creation Handler (inc/db.php)

File Location: wp-content/plugins/msr-plugin/inc/db.php

<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * Creates custom plugin database tables upon activation.
 */
function msr_create_db_tables() {
    global $wpdb;

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

    // Retrieve database character collation
    $charset_collate = $wpdb->get_charset_collate();

    // SQL statement with strict dbDelta formatting
    $sql = "CREATE TABLE IF NOT EXISTS $table_name (
        id bigint(20) NOT NULL AUTO_INCREMENT,
        post_id bigint(20) NOT NULL,
        user_id bigint(20) NOT NULL,
        reaction_type varchar(50) NOT NULL,
        reaction_count int(11) DEFAULT 0 NOT NULL,
        created_at datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
        updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL,
        PRIMARY KEY  (id),
        KEY post_id  (post_id),
        KEY user_id  (user_id)
    ) $charset_collate;";

    // Require WordPress upgrade library for dbDelta
    require_once ABSPATH . 'wp-admin/includes/upgrade.php';

    // Execute dbDelta to build/update table structure
    dbDelta( $sql );

    // Store database version in wp_options
    add_option( 'msr_db_version', MSR_DB_VERSION );
}

/**
 * Checks database version and upgrades schema automatically.
 */
function msr_update_db_check() {
    $installed_ver = get_option( 'msr_db_version' );

    // Compare installed database version with target constant
    if ( version_compare( $installed_ver, MSR_DB_VERSION, '<' ) ) {
        global $wpdb;

        $table_name      = $wpdb->prefix . 'reactions';
        $charset_collate = $wpdb->get_charset_collate();

        $sql = "CREATE TABLE IF NOT EXISTS $table_name (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            post_id bigint(20) NOT NULL,
            user_id bigint(20) NOT NULL,
            reaction_type varchar(50) NOT NULL,
            reaction_count int(11) DEFAULT 0 NOT NULL,
            created_at datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
            updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL,
            PRIMARY KEY  (id),
            KEY post_id  (post_id),
            KEY user_id  (user_id)
        ) $charset_collate;";

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

        // Update option record to match new version
        update_option( 'msr_db_version', MSR_DB_VERSION );
    }
}
Line-by-Line Detailed Explanation:
  1. global $wpdb;: Grants access to the WordPress database abstraction object.
  2. $table_name = $wpdb->prefix . 'reactions';: Concatenates the site-specific prefix (e.g., wp_) with the custom table name to generate wp_reactions.
  3. $charset_collate = $wpdb->get_charset_collate();: Pulls the active character set and collation from WordPress environment settings.
  4. require_once ABSPATH . 'wp-admin/includes/upgrade.php';: Explicitly includes the core WordPress file containing the dbDelta() function, as dbDelta() is not loaded during standard front-end requests.
  5. dbDelta( $sql );: Parses and executes the SQL schema declaration.
  6. add_option( 'msr_db_version', MSR_DB_VERSION );: Saves the initial schema version into wp_options.
  7. if ( version_compare( $installed_ver, MSR_DB_VERSION, '<' ) ): Evaluates whether the installed DB version in wp_options is older than the current constant. If true, re-runs dbDelta() to apply schema alterations and calls update_option() to update the version string.

WordPress Technical Reference Guide

Table: Essential Action Hooks for Database Operations

Hook NameTarget Execution StagePrimary Use Case in Database Management
register_activation_hookExecuted when user activates plugin in WP-Admin.Create initial database tables, insert default data, and set DB version in wp_options.
register_deactivation_hookExecuted when user deactivates plugin in WP-Admin.Clear scheduled cron jobs or temporary cache files (do NOT drop tables on deactivation).
register_uninstall_hookExecuted when user deletes plugin permanently from WP-Admin.Drop custom database tables (DROP TABLE) and delete version options (delete_option).
plugins_loadedExecuted after all active plugins are fully loaded by WordPress core.Run automated schema updates by checking get_option('msr_db_version') against MSR_DB_VERSION.

Table: Core $wpdb Methods & Properties

Member NameTypeDescription & Usage
$wpdb->prefixProperty (string)Stores the site-specific database table prefix (e.g., wp_). Concatenate with table names.
$wpdb->get_charset_collate()Method (string)Returns formatted character set and collation string (e.g., DEFAULT CHARACTER SET utf8mb4...).
$wpdb->insert()Method (`int\false`)
$wpdb->update()Method (`int\false`)
$wpdb->delete()Method (`int\false`)
$wpdb->get_results()Method (array)Executes SQL queries and returns multi-row results as objects, associative arrays, or indexed arrays.
$wpdb->prepare()Method (string)Prepares raw SQL statements safely using format specifiers (%s, %d, %f) to prevent SQL Injection.

Table: dbDelta() Required SQL Formatting Syntax Rules

Rule ComponentRequirementCorrect Formatting ExampleIncorrect / Invalid Example
Primary Key SpacingMust have 2 spaces after PRIMARY KEYPRIMARY KEY (id)PRIMARY KEY (id) (Single space fails)
Index KeywordMust use KEY, not INDEXKEY post_id (post_id)INDEX post_id (post_id)
SQL Keywords CaseMust be UPPERCASECREATE TABLE, NOT NULLcreate table, not null
Line SeparationsOne column/key declaration per lineEach field on new lineMultiple fields combined on one line
Data TypesMust explicitly define type & sizevarchar(50) NOT NULLvarchar NOT NULL (Missing length)

Practical Step-by-Step Plugin Implementation Guide

Follow these steps to create, verify, and upgrade custom plugin database tables locally.

Step 1: Create Main Plugin File & Constant Setup

Inside wp-content/plugins/msr-db-demo/, create msr-db-demo.php:

<?php
/**
 * Plugin Name: MSR Custom DB Table Demo
 * Description: Demonstrates custom MySQL table creation and automated migrations.
 * Version: 1.0.0
 * Author: CSE Study247
 */

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

define( 'MSR_DB_DEMO_PATH', plugin_dir_path( __FILE__ ) );
define( 'MSR_DB_DEMO_VERSION', '1.0.0' );

require_once MSR_DB_DEMO_PATH . 'inc/db-handler.php';

// Register activation hook in main file
register_activation_hook( __FILE__, 'msr_db_demo_setup' );

// Automated schema migration check
add_action( 'plugins_loaded', 'msr_db_demo_migration_check' );

Step 2: Implement Database Handler Functions

Create msr-db-demo/inc/db-handler.php:

<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

function msr_db_demo_setup() {
    global $wpdb;

    $table_name      = $wpdb->prefix . 'post_votes';
    $charset_collate = $wpdb->get_charset_collate();

    $sql = "CREATE TABLE IF NOT EXISTS $table_name (
        id bigint(20) NOT NULL AUTO_INCREMENT,
        post_id bigint(20) NOT NULL,
        vote_type varchar(20) NOT NULL,
        vote_count int(11) DEFAULT 0 NOT NULL,
        created_at datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
        PRIMARY KEY  (id),
        KEY post_id  (post_id)
    ) $charset_collate;";

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

    add_option( 'msr_db_demo_version', MSR_DB_DEMO_VERSION );
}

function msr_db_demo_migration_check() {
    $installed = get_option( 'msr_db_demo_version' );

    if ( version_compare( $installed, MSR_DB_DEMO_VERSION, '<' ) ) {
        msr_db_demo_setup();
        update_option( 'msr_db_demo_version', MSR_DB_DEMO_VERSION );
    }
}

Step 3: Activate Plugin & Verify in phpMyAdmin

  1. Navigate to WP-Admin -> Plugins and click Activate on MSR Custom DB Table Demo.
  2. Open phpMyAdmin (or your MySQL database client) and select your WordPress database (wp_plugin or local dev DB).
  3. Verify Table: Confirm that the table wp_post_votes exists with columns id, post_id, vote_type, vote_count, and created_at.
  4. Verify Option Record: Open the wp_options table and search for option_name = 'msr_db_demo_version'. Confirm value is '1.0.0'.

Step 4: Test Schema Upgrades

  1. Update define( 'MSR_DB_DEMO_VERSION', '1.0.1' ); in msr-db-demo.php.
  2. Add a new column declaration (e.g., user_id bigint(20) NOT NULL,) to $sql in db-handler.php.
  3. Refresh any page in WP-Admin.
  4. Verify Migration: Inspect wp_post_votes in phpMyAdmin; confirm user_id column was added automatically, and wp_options shows version '1.0.1'.

Common Pitfalls, Security Vulnerabilities & Best Practices

1. Calling register_activation_hook() in Subdirectories

  • The Error: Invoking register_activation_hook( __FILE__, 'callback' ) inside inc/db-handler.php.
  • Symptom: Activation hook fails to execute; database table is not created upon plugin activation.
  • Fix: Always call register_activation_hook() in the root main plugin file (msr-db-demo.php), passing the main plugin file path.

2. dbDelta() Syntax Violations

  • The Error: Using single space after PRIMARY KEY (id) or using INDEX instead of KEY.
  • Symptom: dbDelta() silently fails to create keys or duplicates column definitions during table updates.
  • Fix: Strictly enforce uppercase SQL keywords, two spaces after PRIMARY KEY (id), and the KEY keyword for indexes.

3. Dropping Tables on Plugin Deactivation

  • The Error: Calling DROP TABLE inside register_deactivation_hook().
  • Symptom: When site admins temporarily deactivate a plugin for troubleshooting, all client database records are permanently destroyed.
  • Fix: Never delete database tables on deactivation. Table deletion should occur only inside an explicit uninstall.php file when the user permanently deletes the plugin.

4. Raw SQL Injections in Custom Database Queries

  • The Error: Concatenating unescaped user input into $wpdb->query( "SELECT * FROM $table WHERE id = " . $_GET['id'] ).
  • Symptom: Critical SQL Injection (SQLi) security vulnerability allowing attackers to dump database contents or overwrite administrative privileges.
  • Fix: Always use $wpdb->prepare() for custom SQL queries containing dynamic variables: $wpdb->prepare( "SELECT * FROM $table WHERE id = %d", intval( $_GET['id'] ) ).

Cumulative Technical Interview Preparation (25 Questions)

What function does WordPress provide to safely create and modify custom database tables?

  • Answer: dbDelta(). It examines existing table structures and applies required schema changes without dropping tables or overwriting data.
  • Follow-Up Question: Where is dbDelta() defined in WordPress core?
    • Answer: It is defined in wp-admin/includes/upgrade.php and must be explicitly imported using require_once ABSPATH . 'wp-admin/includes/upgrade.php';.

What global variable provides access to the WordPress database layer?

  • Answer: $wpdb. It is an instance of the wpdb class defined in wp-includes/wp-db.php.
  • Follow-Up Question: How do you reference the site’s dynamic database prefix using $wpdb?
    • Answer: Access the $wpdb->prefix property (e.g., $wpdb->prefix . 'my_table').

Why should you append $wpdb->get_charset_collate() to CREATE TABLE queries?

  • Answer: It retrieves the site’s configured database character set and collation (e.g., utf8mb4), ensuring full Unicode/emoji support and database compatibility.
  • Follow-Up Question: What happens if you omit collation settings on a multi-lingual site?
    • Answer: Characters from different character sets may render corrupted (mojibake) or trigger MySQL encoding errors.

Which action hook should be used to execute initial database table creation code?

  • Answer: register_activation_hook(). It executes when a plugin is activated in WP-Admin.
  • Follow-Up Question: Why should database creation NOT be hooked directly to init?
    • Answer: Hooking table creation to init runs dbDelta() on every single HTTP page load, degrading server performance.

What database table stores plugin DB version records?

  • Answer: wp_options. Stored using add_option() or update_option().
  • Follow-Up Question: Why is tracking DB version strings necessary?
    • Answer: It allows plugins to check whether the installed schema matches the current codebase version and trigger automated updates.

Intermediate Questions

Why does calling register_activation_hook(__FILE__, 'callback') inside inc/db.php fail to trigger?

  • Answer: In inc/db.php, __FILE__ resolves to the subdirectory file path. WordPress checks activation hooks against root main plugin paths, so the hook is ignored.
  • Follow-Up Question: How do you fix this architectural issue?
    • Answer: Place register_activation_hook() in the main root plugin file (msr-plugin.php) and call the setup function located in inc/db.php.

What are two mandatory syntax rules required by dbDelta()?

  • Answer: (1) Two spaces must follow PRIMARY KEY (id). (2) Every field declaration must appear on its own line.
  • Follow-Up Question: What keyword must be used for declaring non-primary key indexes in dbDelta()?
    • Answer: The keyword KEY (not INDEX), followed by a key name and two spaces: KEY index_name (column_name).

How do you execute automatic database schema upgrades when a user updates a plugin without deactivating it?

  • Answer: Hook a version migration function to plugins_loaded. Compare get_option('my_db_version') against a version constant (MY_DB_VERSION). If the option is older, run dbDelta() and update the option.
  • Follow-Up Question: Why won’t register_activation_hook handle plugin updates automatically?
    • Answer: Activation hooks execute only during manual plugin activation, not during automatic plugin updates via the WP-Admin updates panel.

What is the difference between register_deactivation_hook and uninstall.php regarding database cleanup?

  • Answer: register_deactivation_hook runs when a plugin is temporarily deactivated; it should never delete database tables. uninstall.php runs when a plugin is permanently deleted; it is the correct location for dropping custom tables (DROP TABLE).
  • Follow-Up Question: How does WordPress execute uninstall.php?
    • Answer: WordPress executes uninstall.php directly in isolation when an admin deletes the plugin from WP-Admin.

Why is using wp_postmeta for storing millions of user analytics records bad practice?

  • Answer: wp_postmeta uses unindexed meta_value text fields and generic key structures. Storing millions of rows creates huge database tables and slow SQL joins, hurting overall site performance.
  • Follow-Up Question: What performance features do custom MySQL tables offer over wp_postmeta?
    • Answer: Custom typed columns (BIGINT, DATETIME), specific indexes, foreign keys, and compact storage layout.

Advanced Questions

How do you safely format dynamic values inside custom database queries to prevent SQL Injection?

  • Answer: Use $wpdb->prepare(). Example: $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}votes WHERE post_id = %d AND type = %s", $post_id, $type ).
  • Follow-Up Question: What format specifiers are supported by $wpdb->prepare()?
    • Answer: %d for integers, %f for floats, and %s for strings.

What occurs if dbDelta() encounters a column in your SQL query that already exists in the target table?

  • Answer: dbDelta() compares the existing column definition with the new declaration. If attributes differ (e.g., increased field length), dbDelta() alters the column; if identical, it leaves existing data intact.
  • Follow-Up Question: Does dbDelta() remove columns from a database table if they are removed from the SQL string?
    • Answer: No. dbDelta() never drops columns or tables automatically to prevent accidental data loss.

How does $wpdb->insert() handle data formatting and escaping under the hood?

  • Answer: $wpdb->insert( $table, $data_array, $format_array ) accepts arrays of key-value pairs and format specifiers (%s, %d), automatically escaping inputs and executing a prepared statement.
  • Follow-Up Question: What does $wpdb->insert() return on success versus failure?
    • Answer: Returns the number of inserted rows (1) on success, or false on failure.

Describe how to handle multi-site network plugin database table creation (wpmu_new_blog).

  • Answer: In a Multisite network, plugins must loop through all network blogs (get_sites()) and create prefix-specific tables (e.g., wp_2_reactions), or hook into wpmu_new_blog to create tables automatically whenever a new sub-site is provisioned.
  • Follow-Up Question: What property gives the base prefix across network sites versus the current site prefix?
    • Answer: $wpdb->base_prefix provides the main network prefix (wp_), while $wpdb->prefix provides the current blog prefix (wp_2_).

What is the purpose of $wpdb->show_errors() and $wpdb->hide_errors() during plugin development?

  • Answer: $wpdb->show_errors() enables output of SQL error messages directly to the screen or debug log for troubleshooting. $wpdb->hide_errors() suppresses SQL errors on production sites to prevent sensitive path exposure.
  • Follow-Up Question: How do you inspect the last executed SQL query string in $wpdb?
    • Answer: Inspect the $wpdb->last_query property or check $wpdb->last_error for the last failure message.

Coding Questions

Write code to declare a custom table prefix $table_name for a table named user_logs.

global $wpdb;
$table_name = $wpdb->prefix . 'user_logs';

Write code to load upgrade.php and execute dbDelta() safely inside a plugin function.

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

Correct the syntax errors in the following dbDelta() SQL snippet:

Buggy Code:

create table wp_my_logs (
id int(11) NOT NULL AUTO_INCREMENT,
log_msg varchar(255),
PRIMARY KEY (id)
)

Corrected Code:

CREATE TABLE wp_my_logs (
    id int(11) NOT NULL AUTO_INCREMENT,
    log_msg varchar(255) NOT NULL,
    PRIMARY KEY  (id)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

Explanation: Uppercased SQL keywords, added missing field requirement (NOT NULL), added two spaces after PRIMARY KEY (id), and appended character collation.

Write a complete activation hook function that creates a wp_events table with columns id, event_name, and event_date.

function msr_create_events_table() {
    global $wpdb;

    $table_name      = $wpdb->prefix . 'events';
    $charset_collate = $wpdb->get_charset_collate();

    $sql = "CREATE TABLE IF NOT EXISTS $table_name (
        id bigint(20) NOT NULL AUTO_INCREMENT,
        event_name varchar(100) NOT NULL,
        event_date datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
        PRIMARY KEY  (id)
    ) $charset_collate;";

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

    add_option( 'msr_events_db_version', '1.0.0' );
}

Write code to safely insert a record into $table_name using $wpdb->insert().

global $wpdb;
$table_name = $wpdb->prefix . 'events';

$wpdb->insert(
    $table_name,
    array(
        'event_name' => 'WordPress Workshop',
        'event_date' => current_time( 'mysql' ),
    ),
    array(
        '%s',
        '%s',
    )
);

Scenario-Based Questions

A developer creates a table using dbDelta(), but notice logs show Call to undefined function dbDelta(). Why did this happen?

  • Answer: dbDelta() is defined inside wp-admin/includes/upgrade.php, which is loaded only in WP-Admin screens. The developer forgot to include require_once ABSPATH . 'wp-admin/includes/upgrade.php'; before calling dbDelta().

Your custom plugin table is missing on client sites with custom prefixes (e.g., site_). Hardcoded SQL queries use CREATE TABLE wp_my_table. How do you fix this?

  • Answer: Replace hardcoded wp_ strings with dynamic $wpdb->prefix concatenation: $table_name = $wpdb->prefix . 'my_table';.

An updated version of your plugin adds a status column to a custom table, but existing users report SQL errors. You relied solely on register_activation_hook. What went wrong?

  • Answer: register_activation_hook runs only when plugins are manually activated. Users updating via the WP-Admin plugin updater bypassed activation. Fix it by adding a DB version check on plugins_loaded that re-runs dbDelta().

A site administrator reports that deactivating your plugin erased all client order records stored in your custom table. How do you resolve this design flaw?

  • Answer: Remove table deletion code (DROP TABLE) from register_deactivation_hook(). Move table cleanup code strictly to uninstall.php, ensuring data persists during temporary plugin deactivations.

A client reports SQL injection security alerts from a security plugin targeting your custom query: $wpdb->query("SELECT * FROM $table WHERE type = '$type'"). How do you remediate?

  • Answer: Refactor the query using $wpdb->prepare(): $wpdb->query( $wpdb->prepare( "SELECT * FROM $table WHERE type = %s", $type ) ).

Interactive Practice & Skill Assessment

Which core file contains the dbDelta() function declaration?

  • A) wp-includes/taxonomy.php
  • B) wp-admin/includes/upgrade.php
  • C) wp-includes/wp-db.php
  • D) wp-settings.php
  • Answer: B
  • Explanation: dbDelta() is located inside wp-admin/includes/upgrade.php and must be imported explicitly before execution.

What property of $wpdb returns the dynamic table prefix?

  • A) $wpdb->table_prefix
  • B) $wpdb->db_prefix
  • C) $wpdb->prefix
  • D) $wpdb->site_prefix
  • Answer: C
  • Explanation: $wpdb->prefix contains the site-specific prefix string (e.g., wp_).

How many spaces must follow the phrase PRIMARY KEY in a dbDelta() SQL statement?

  • A) Zero
  • B) Exactly one space
  • C) Exactly two spaces
  • D) Three spaces
  • Answer: C
  • Explanation: dbDelta() parser rules strictly require two spaces following PRIMARY KEY (id).

Which hook is best suited for running automatic schema migrations when plugin files are updated?

  • A) init
  • B) plugins_loaded
  • C) wp_head
  • D) admin_menu
  • Answer: B
  • Explanation: plugins_loaded runs early after all active plugins load, making it ideal for version comparison checks.

What keyword must be used to declare non-primary key indexes in dbDelta()?

  • A) INDEX
  • B) KEY
  • C) UNIQUE INDEX
  • D) FOREIGN KEY
  • Answer: B
  • Explanation: dbDelta() requires the keyword KEY for index declarations.

Where must register_activation_hook() be declared for reliable execution?

  • A) Inside any included PHP file within inc/
  • B) Inside uninstall.php
  • C) Inside the root main plugin file (msr-plugin.php)
  • D) Inside functions.php of the active theme
  • Answer: C
  • Explanation: Calling register_activation_hook() in the main plugin file ensures __FILE__ resolves to the primary plugin path.

What function updates an existing option value in wp_options?

  • A) set_option()
  • B) update_option()
  • C) save_option()
  • D) modify_option()
  • Answer: B
  • Explanation: update_option() updates existing option records or creates them if missing.

Which $wpdb method formats dynamic variables safely to prevent SQL Injection?

  • A) $wpdb->escape()
  • B) $wpdb->sanitize()
  • C) $wpdb->prepare()
  • D) $wpdb->protect()
  • Answer: C
  • Explanation: $wpdb->prepare() uses format specifiers (%s, %d) to prepare SQL statements safely.

True or False: dbDelta() automatically drops columns from database tables if they are deleted from your SQL query string.

  • A) True
  • B) False
  • Answer: B
  • Explanation: dbDelta() never drops columns or tables automatically to protect user data from accidental deletion.

What $wpdb method returns database character set and collation defaults?

  • A) $wpdb->get_charset_collate()
  • B) $wpdb->get_encoding()
  • C) $wpdb->get_db_charset()
  • D) $wpdb->collation()
  • Answer: A
  • Explanation: $wpdb->get_charset_collate() returns formatted character set and collation strings.

Hands-On Coding Exercises

Exercise 1: Custom DB Table Schema Setup

Write a function create_logs_table() that defines a custom table wp_activity_logs containing id (auto-increment primary key), user_id (bigint), activity (varchar 255), and log_date (datetime).

// Solution
function create_logs_table() {
    global $wpdb;

    $table_name      = $wpdb->prefix . 'activity_logs';
    $charset_collate = $wpdb->get_charset_collate();

    $sql = "CREATE TABLE IF NOT EXISTS $table_name (
        id bigint(20) NOT NULL AUTO_INCREMENT,
        user_id bigint(20) NOT NULL,
        activity varchar(255) NOT NULL,
        log_date datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
        PRIMARY KEY  (id),
        KEY user_id  (user_id)
    ) $charset_collate;";

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

Exercise 2: Secure Database Record Insertion

Write code using $wpdb->insert() to save an activity log entry (user_id = 5, activity = 'User logged in').

// Solution
global $wpdb;
$table_name = $wpdb->prefix . 'activity_logs';

$wpdb->insert(
    $table_name,
    array(
        'user_id'  => 5,
        'activity' => 'User logged in',
        'log_date' => current_time( 'mysql' ),
    ),
    array(
        '%d',
        '%s',
        '%s',
    )
);

Exercise 3: Automated Database Migration Handler

Write a function hooked to plugins_loaded that checks if msr_logs_db_version in wp_options is less than '1.1.0', runs create_logs_table(), and updates the version option.

// Solution
define( 'MSR_LOGS_DB_VERSION', '1.1.0' );

function msr_check_logs_migration() {
    $installed = get_option( 'msr_logs_db_version' );

    if ( version_compare( $installed, MSR_LOGS_DB_VERSION, '<' ) ) {
        create_logs_table();
        update_option( 'msr_logs_db_version', MSR_LOGS_DB_VERSION );
    }
}
add_action( 'plugins_loaded', 'msr_check_logs_migration' );

Exercise 4: Safe Prepared Query Execution

Write a query using $wpdb->prepare() and $wpdb->get_results() to fetch all activity logs for a specific user_id passed via $_GET['user_id'].

// Solution
global $wpdb;
$user_id = isset( $_GET['user_id'] ) ? intval( $_GET['user_id'] ) : 0;

if ( $user_id > 0 ) {
    $table_name = $wpdb->prefix . 'activity_logs';
    $query      = $wpdb->prepare( "SELECT * FROM $table_name WHERE user_id = %d ORDER BY log_date DESC", $user_id );
    $results    = $wpdb->get_results( $query );
}

Exercise 5: Debugging dbDelta() Formatting Errors

Fix the formatting errors in the following SQL string so dbDelta() processes it correctly:

// BROKEN SQL
$sql = "create table " . $wpdb->prefix . "notes (
id int(11) NOT NULL AUTO_INCREMENT,
note text,
PRIMARY KEY(id)
);";
// CORRECTED SOLUTION
$table_name      = $wpdb->prefix . 'notes';
$charset_collate = $wpdb->get_charset_collate();

$sql = "CREATE TABLE IF NOT EXISTS $table_name (
    id int(11) NOT NULL AUTO_INCREMENT,
    note text NOT NULL,
    PRIMARY KEY  (id)
) $charset_collate;";

5-Minute Core Takeaways

  1. Custom Tables vs Options: Use wp_options for basic settings; create custom MySQL tables for high-volume transactional data (e.g., votes, logs, analytics).
  2. Global $wpdb Layer: Use $wpdb->prefix for table prefixes and $wpdb->get_charset_collate() for collation.
  3. dbDelta() Formatting: Uppercase SQL keywords, separate lines per field, two spaces after PRIMARY KEY (id), and use KEY for index declarations.
  4. Activation Hook Scope: Declare register_activation_hook() inside the main root plugin file (msr-plugin.php).
  5. Schema Migrations: Track schema version in wp_options; compare version constants and update schema on plugins_loaded.

Syntax & Code Cheatsheet

// 1. Access Global $wpdb Layer
global $wpdb;
$table_name      = $wpdb->prefix . 'my_table';
$charset_collate = $wpdb->get_charset_collate();

// 2. Formulate dbDelta SQL Statement
$sql = "CREATE TABLE IF NOT EXISTS $table_name (
    id bigint(20) NOT NULL AUTO_INCREMENT,
    user_id bigint(20) NOT NULL,
    meta_val varchar(100) NOT NULL,
    created_at datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
    PRIMARY KEY  (id),
    KEY user_id  (user_id)
) $charset_collate;";

// 3. Load Upgrade Library & Run dbDelta
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
dbDelta( $sql );

// 4. Save/Update DB Version in Options
add_option( 'my_plugin_db_version', '1.0.0' );

// 5. Automated Migration on plugins_loaded
add_action( 'plugins_loaded', function() {
    if ( version_compare( get_option( 'my_plugin_db_version' ), '1.0.1', '<' ) ) {
        // Run dbDelta update logic
        update_option( 'my_plugin_db_version', '1.0.1' );
    }
});



Scroll to Top