-
Notifications
You must be signed in to change notification settings - Fork 5
Custom Tables
The custom tables into WordPress are handled into the $wpdb global object.
When deadling with custom tables, there is two approaches :
- Global multisite table
- Site by site table, created on activation
To make your custom tables compatible with WordPress (switch to blog for example) you need to do this in the main plugin file :
// Plugin tables
global $wpdb;
$wpdb->tables[] = 'sample_table';
$wpdb->sample_table = $wpdb->prefix . 'sample_table';
Where sample_table is the real name of your table. This is important because WordPress will search/replace this name in the case of switch_to_blog.
To make your custom tables compatible with WordPress on mulsite you need to do :
// Plugin tables
global $wpdb;
$wpdb->ms_global_tables[] = 'sample_table';
$wpdb->sample_table = $wpdb->prefix . 'sample_table';
Where sample_table is the real name of your table. This will not replace the table name on a switch_to_blog call.
When activating the plugin, the method BEA\PB\Plugin::activation is called, this is the right place to create your tables. This can be achieved like this :
public static function activate() {
global $wpdb;
if ( ! empty( $wpdb->charset ) ) {
$charset_collate = "DEFAULT CHARACTER SET $wpdb->charset";
}
if ( ! empty( $wpdb->collate ) ) {
$charset_collate .= " COLLATE $wpdb->collate";
}
// Add one library admin function for next function
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
// Data table
maybe_create_table( $wpdb->sample_table, "CREATE TABLE IF NOT EXISTS `{$wpdb->sample_table}` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`post_id` bigint(20) NOT NULL,
PRIMARY KEY (`id`)
) $charset_collate AUTO_INCREMENT=1;" );
}