WordPress Database Charset/Collate

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

Leave a Comment