Is there an easy way of getting the charset and collation of the DB tables in WordPress without resorting to SQL queries?
There are $wpdb->charset
and $wpdb->collate
. I am not sure if or when one of these values might be empty, so it is better to prepare for empty values …
From my DB class:
/**
* Get table charset and collation.
*
* @since 2012.10.22
* @return string
*/
protected static function get_wp_charset_collate() {
global $wpdb;
$charset_collate = '';
if ( ! empty ( $wpdb->charset ) )
$charset_collate = "DEFAULT CHARACTER SET $wpdb->charset";
if ( ! empty ( $wpdb->collate ) )
$charset_collate .= " COLLATE $wpdb->collate";
return $charset_collate;
}
Used to create a table like this:
global $wpdb;
// encoding
$charset_collate = self::get_wp_charset_collate();
$table = self::get_table_name();
// the user could have just deleted the plugin without running the clean up.
$sql = "CREATE TABLE IF NOT EXISTS $table (
ID bigint unsigned NOT NULL auto_increment,
event_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
event_group tinytext,
event_title text,
PRIMARY KEY (ID)
) $charset_collate;";
// make dbDelta() available
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
dbDelta( $sql );
Related: Problem with blog charset UTF-7
The file wp-admin/includes/upgrade.php
includes wp-admin/includes/schema.php
. This at the top declare as global (see source):
// Declare these as global in case schema.php is included from a function.
global $wpdb, $wp_queries, $charset_collate;
...
$charset_collate = '';
if ( ! empty( $wpdb->charset ) )
$charset_collate = "DEFAULT CHARACTER SET $wpdb->charset";
if ( ! empty( $wpdb->collate ) )
$charset_collate .= " COLLATE $wpdb->collate";
So you can follow @Toscho's answer and check $wpdb
. Or, using Toscho's example:
global $wpdb, $charset_collate;
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
$sql = "CREATE TABLE $table (
ID bigint unsigned NOT NULL auto_increment,
event_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
event_group tinytext,
event_title text,
PRIMARY KEY (ID)
) $charset_collate;";
dbDelta( $sql );
Note the IF NOT EXISTS
is not required as dbDelta()
handles this.