How to Create a Custom Table in WordPress via functions.php: A Complete Guide to MySQL Data Types


Sometimes, standard WordPress features like Posts and Meta Fields aren’t enough for complex projects. In such cases, creating your own database table is the most efficient way to optimize performance and data structure.

1. Reference Code for Creating a Table

To interact with the database, we use the dbDelta function. Its main advantage is “smart” updates: if the table already exists, it won’t recreate it; instead, it will simply update the structure (e.g., if you add a new column later).

Add this code to your theme’s functions.php file:

function create_custom_table() {
    global $wpdb;

    // Table name with prefix (e.g., wp_custom_table)
    $table_name = $wpdb->prefix . 'custom_table'; 

    // Get the site's character set (usually utf8mb4)
    $charset_collate = $wpdb->get_charset_collate();

    $sql = "CREATE TABLE $table_name (
        id INT NOT NULL AUTO_INCREMENT,
        column_name1 VARCHAR(255) NOT NULL,
        column_name2 TEXT NOT NULL,
        column_name3 INT DEFAULT 0,
        PRIMARY KEY  (id)
    ) $charset_collate;";

    // Include the necessary file for dbDelta
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
}

// Trigger the function during theme setup
add_action('after_setup_theme', 'create_custom_table');

2. Essential MySQL Data Types

To ensure your table is fast and storage-efficient, it’s crucial to choose the right data type for each column.

Numeric Types

Type Description Use Case
INT Whole number (up to 4 billion). IDs, counters, product quantities.
TINYINT Very small integer (-128 to 127). Statuses (0 or 1), “yes/no” settings.
DECIMAL Exact fixed-point number. Money and prices. E.g., DECIMAL(10,2).

String Types (Text)

Type Description Use Case
VARCHAR(N) Variable-length string (up to N). Titles, emails, names (usually 255).
TEXT Long text (up to 65 KB). Descriptions, comments, JSON data.
LONGTEXT Very long text (up to 4 GB). Logs or massive articles.

Date and Time

Type Description Use Case
DATETIME Date and time (YYYY-MM-DD HH:MM:SS). Order date or registration date.
TIMESTAMP Seconds since 1970 (Unix Epoch). Automatic “last modified” tracking.

3. Critical dbDelta Syntax Rules





The dbDelta function is notoriously picky about SQL formatting. If you ignore these rules, the table simply won’t be created:

  1. Double Space: There must be two spaces between the words PRIMARY KEY and the key definition (id).

  2. Uppercase: Write all SQL commands (CREATE TABLE, NOT NULL, INT) in uppercase.

  3. VARCHAR Length: You must specify a length for VARCHAR columns, such as VARCHAR(255).

How to Verify the Result?

After saving your functions.php file, simply refresh any page on your website. Then, log into phpMyAdmin. You should see the new entry wp_custom_table in your database table list.

Как создать таблицу в WordPress через functions.php: Полный гид по типам данных