Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Is there an easy way of getting the charset and collation of the DB tables in WordPress without resorting to SQL queries?

share|improve this question

2 Answers 2

up vote 2 down vote accepted

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

share|improve this answer

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.