Puddinq.com sharing knowledge

Create custom tables in WordPress

Create custom tables in WordPress

It is advised to use the default database structure with custom posts and meta fields to store information, but sometimes when you have specific needs or want to scale the proportions of what is happening you want custom tables for your data. Here is a snippet that uses the global $wpdb end a default function maybe_create_table() to create one table:

    function installTables() {

        global $wpdb;

        // we need this to access the maybe_create_table function
        require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );

        $charset_collate = $wpdb->get_charset_collate();
        $table_tasks = $wpdb->prefix . "tasks";
        $columns_tasks = <<<COLUMNS
  `project_id` int(11) NOT NULL,
  `title` varchar(250) NOT NULL,
  `content` longtext NOT NULL,
  KEY `project_id` (`project_id`)

        // we are using this function so that if the table already exists, there are no complications
        maybe_create_table( $wpdb->prefix . $table_name, "CREATE TABLE {$table_tasks} {$columns_tasks} {$charset_collate};" );


We are using maybe_create_table so that if this function is called in your register_activation_hook and the table already exists there will be no complications. This can be a good thing if removing the database is optional when uninstalling your theme or plugin.