Skip to content

Instantly share code, notes, and snippets.

@sudar
Last active September 10, 2022 17:59
Show Gist options
  • Save sudar/9927194 to your computer and use it in GitHub Desktop.
Save sudar/9927194 to your computer and use it in GitHub Desktop.
How To Properly Create Tables In WordPress Multisite Plugins. Explanation at http://sudarmuthu.com/blog/how-to-properly-create-tables-in-wordpress-multisite-plugins/
<?php
// Creating tables in Single site installations
function on_activate() {
create_table();
}
function create_table() {
global $wpdb;
$table_name = $wpdb->prefix . 'table_name';
if( $wpdb->get_var( "show tables like '{$table_name}'" ) != $table_name ) {
$sql = "CREATE TABLE " . $table_name . " (
id mediumint(9) NOT NULL AUTO_INCREMENT,
col VARCHAR(100) NOT NULL,
PRIMARY KEY (id)
);";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
add_option( EmailLog::DB_OPTION_NAME, EmailLog::DB_VERSION );
}
}
register_activation_hook( __FILE__, 'on_activate' );
?>
<?php
// Creating tables for all blogs in a WordPress Multisite installation
function on_activate( $network_wide ) {
global $wpdb;
if ( is_multisite() && $network_wide ) {
// Get all blogs in the network and activate plugin on each one
$blog_ids = $wpdb->get_col( "SELECT blog_id FROM $wpdb->blogs" );
foreach ( $blog_ids as $blog_id ) {
switch_to_blog( $blog_id );
create_table();
restore_current_blog();
}
} else {
create_table();
}
}
register_activation_hook( __FILE__, 'on_activate' );
?>
<?php
// Creating table whenever a new blog is created
function on_create_blog( $blog_id, $user_id, $domain, $path, $site_id, $meta ) {
if ( is_plugin_active_for_network( 'plugin-name/plugin-name.php' ) ) {
switch_to_blog( $blog_id );
create_table();
restore_current_blog();
}
}
add_action( 'wpmu_new_blog', 'on_create_blog', 10, 6 );
?>
<?php
// Deleting the table whenever a blog is deleted
function on_delete_blog( $tables ) {
global $wpdb;
$tables[] = $wpdb->prefix . 'table_name';
return $tables;
}
add_filter( 'wpmu_drop_tables', 'on_delete_blog' );
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment