Skip to content

Instantly share code, notes, and snippets.

@pyksid
Created July 25, 2018 19:56
Show Gist options
  • Save pyksid/4b72d41c521e30d230826d6942e7b83e to your computer and use it in GitHub Desktop.
Save pyksid/4b72d41c521e30d230826d6942e7b83e to your computer and use it in GitHub Desktop.
Convert WordPress database to utf8mb4
<?php
/*
Plugin Name: utf8mb4-convert
Version: 1.0
*/
function update_db_to_utf8mb4()
{
set_time_limit(MINUTE_IN_SECONDS * 30);
if (!isset($_GET['update-utf8mb4'])) {
return;
}
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
require_once ABSPATH . 'wp-admin/includes/admin.php';
require_once ABSPATH . 'wp-admin/includes/schema.php';
global $wpdb;
if (is_multisite()) {
$tables = $wpdb->tables('blog');
} else {
$tables = $wpdb->tables('all');
if (!wp_should_upgrade_global_tables()) {
$global_tables = $wpdb->tables('global');
$tables = array_diff_assoc($tables, $global_tables);
}
}
foreach ($tables as $table) {
maybe_convert_table_to_utf8mb4($table);
}
$wpdb->query("ALTER DATABASE {$wpdb->dbname} CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;");
$tables = $wpdb->get_results("
SELECT table_name, engine
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA='{$wpdb->dbname}'
AND TABLE_COLLATION!='utf8mb4_unicode_ci'
AND TABLE_TYPE='BASE TABLE';
");
foreach ($tables as $table) {
if (preg_match('/^wp_(spbc|cleantalk)/', $table->table_name)) {
continue;
}
$wpdb->query("ALTER TABLE $table->table_name ENGINE = InnoDB;");
$wpdb->query("ALTER TABLE $table->table_name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;");
}
echo 'DB converted to utf8mb4';
die;
}
add_action('wp_loaded', 'update_db_to_utf8mb4');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment