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
(
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `project_id` int(11) NOT NULL,
  `title` varchar(250) NOT NULL,
  `content` longtext NOT NULL,
  PRIMARY KEY (`ID`),
  KEY `project_id` (`project_id`)
)
COLUMNS;

        // 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.