Using WordPress ‘maybe_convert_table_to_utf8mb4()’ PHP function

The maybe_convert_table_to_utf8mb4 WordPress PHP function checks if a table only contains utf8 or utf8mb4 columns and converts it to utf8mb4.

Usage

maybe_convert_table_to_utf8mb4( $table );

Example:

maybe_convert_table_to_utf8mb4( 'wp_example_table' );

Parameters

  • $table (string) – Required. The table to convert.

More information

See WordPress Developer Resources: maybe_convert_table_to_utf8mb4

Examples

Convert a custom table to utf8mb4

If you have a custom table named wp_custom_table, you can convert it to utf8mb4 using the following code:

// Check and convert 'wp_custom_table' to utf8mb4
maybe_convert_table_to_utf8mb4( 'wp_custom_table' );

Convert a table during plugin activation

When activating a plugin, you can convert a table to utf8mb4.

// Plugin activation hook
register_activation_hook( __FILE__, 'convert_table_on_activation' );

function convert_table_on_activation() {
    maybe_convert_table_to_utf8mb4( 'wp_another_custom_table' );
}

Convert a table on theme activation

When activating a theme, you can convert a table to utf8mb4.

// Theme activation hook
add_action( 'after_switch_theme', 'convert_table_on_theme_activation' );

function convert_table_on_theme_activation() {
    maybe_convert_table_to_utf8mb4( 'wp_theme_table' );
}

Convert a table after creating a new post

After creating a new post, you can convert a table to utf8mb4.

// Post creation hook
add_action( 'save_post', 'convert_table_after_post_creation', 10, 2 );

function convert_table_after_post_creation( $post_ID, $post ) {
    maybe_convert_table_to_utf8mb4( 'wp_post_related_table' );
}

Convert a table on a custom admin action

When executing a custom admin action, you can convert a table to utf8mb4.

// Custom admin action hook
add_action( 'admin_action_convert_custom_table', 'convert_table_on_custom_admin_action' );

function convert_table_on_custom_admin_action() {
    maybe_convert_table_to_utf8mb4( 'wp_admin_related_table' );
    wp_redirect( admin_url( 'options-general.php?page=my-plugin-settings&converted=1' ) );
    exit;
}