pre_get_table_charset is a WordPress PHP filter that allows you to modify the table charset value before the database is checked.
Usage
add_filter('pre_get_table_charset', 'your_custom_function', 10, 2); function your_custom_function($charset, $table) { // your custom code here return $charset; }
Parameters
- $charset (string|WP_Error|null) – The character set to use, or a WP_Error object if it couldn’t be found. Default is null.
- $table (string) – The name of the table being checked.
More information
See WordPress Developer Resources: https://developer.wordpress.org/reference/hooks/pre_get_table_charset/
Examples
Set a default charset for a specific table
Set the default charset to ‘utf8mb4’ for the ‘wp_custom_table’ table.
add_filter('pre_get_table_charset', 'set_custom_table_charset', 10, 2); function set_custom_table_charset($charset, $table) { if ('wp_custom_table' === $table) { $charset = 'utf8mb4'; } return $charset; }
Set a custom charset for all tables
Set the custom charset ‘custom_charset’ for all tables.
add_filter('pre_get_table_charset', 'set_all_tables_charset', 10, 2); function set_all_tables_charset($charset, $table) { $charset = 'custom_charset'; return $charset; }
Display an error if charset is not found
Return a WP_Error object if the charset is not found.
add_filter('pre_get_table_charset', 'handle_missing_charset', 10, 2); function handle_missing_charset($charset, $table) { if (null === $charset) { $charset = new WP_Error('charset_not_found', __('Charset not found.')); } return $charset; }
Set different charsets for different tables
Set custom charsets for specific tables based on table names.
add_filter('pre_get_table_charset', 'set_table_specific_charset', 10, 2); function set_table_specific_charset($charset, $table) { switch ($table) { case 'wp_table1': $charset = 'utf8'; break; case 'wp_table2': $charset = 'utf8mb4'; break; default: break; } return $charset; }
Set the charset based on a condition
Set the charset to ‘utf8’ if a specific condition is met.
add_filter('pre_get_table_charset', 'set_charset_based_on_condition', 10, 2); function set_charset_based_on_condition($charset, $table) { $condition = true; // Replace with your actual condition if ($condition) { $charset = 'utf8'; } return $charset; }