maybe_convert_table_to_utf8mb4()WP 4.2.0

Converts table fields to the encoding utf8mb4_unicode_ci, if there are fields in the table with encoding utf8_* or utf8mb4_*.

Changes the encoding of all string fields in the table to utf8mb4_unicode_ci, only in the case that:

  1. The table exists.
  2. The collation of all fields is equal to: '' (numeric fields) or starts with 'utf8' or 'utf8mb4' (string fields).
  3. The collation of the table itself does not start with 'utf8mb4'.

In other cases, the function will do nothing.

The function is not defined by default, to make the function work you need to include the file:

require_once ABSPATH . 'wp-admin/includes/upgrade.php';

The function should be run only once upon plugin activation!

No Hooks.

Returns

true|false. Boolean: true - if conversion was successful and false - if not.

Usage

maybe_convert_table_to_utf8mb4( $table );
$table(string) (required)
The name of the table to be converted.

Examples

0

#1 Change the encoding of all table fields to utf8mb4

register_activation_hook( __FILE__, 'myplugin_activate' );
function myplugin_activate() {
	$table = 'my_table';

	require ABSPATH . '/wp-admin/includes/upgrade.php';
	maybe_convert_table_to_utf8mb4( $table );
}

Notes

  • Global. wpdb. $wpdb WordPress database abstraction object.

Changelog

Since 4.2.0 Introduced.

maybe_convert_table_to_utf8mb4() code WP 6.9.1

function maybe_convert_table_to_utf8mb4( $table ) {
	global $wpdb;

	$results = $wpdb->get_results( "SHOW FULL COLUMNS FROM `$table`" );
	if ( ! $results ) {
		return false;
	}

	foreach ( $results as $column ) {
		if ( $column->Collation ) {
			list( $charset ) = explode( '_', $column->Collation );
			$charset         = strtolower( $charset );
			if ( 'utf8' !== $charset && 'utf8mb4' !== $charset ) {
				// Don't upgrade tables that have non-utf8 columns.
				return false;
			}
		}
	}

	$table_details = $wpdb->get_row( "SHOW TABLE STATUS LIKE '$table'" );
	if ( ! $table_details ) {
		return false;
	}

	list( $table_charset ) = explode( '_', $table_details->Collation );
	$table_charset         = strtolower( $table_charset );
	if ( 'utf8mb4' === $table_charset ) {
		return true;
	}

	return $wpdb->query( "ALTER TABLE $table CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci" );
}