What is the correct way for plugins to create tables with special charset/collation considerations?

I think this issue is handled by WooCommerce in their plugin. It also creates its own tables and this is how they take care of Collation part. (I am referring to file class-wc-install.php of WooCommerce). They have written following code in the create_tables function

global $wpdb;

$collate="";

if ( $wpdb->has_cap( 'collation' ) ) {
    if ( ! empty($wpdb->charset ) ) {
        $collate .= "DEFAULT CHARACTER SET $wpdb->charset";
    }
    if ( ! empty($wpdb->collate ) ) {
        $collate .= " COLLATE $wpdb->collate";
    }
}

And then this $collate variable is appended at the end of CREATE TABLE query.

So in this case, query may look like this:

CREATE TABLE plugin_table(
    some_id INT NOT NULL,
    some_data VARCHAR(100) NOT NULL,
    PRIMARY KEY  (some_id)
) $collate;

So they find out WordPress’s Collate and charset and append them.

Hope it helps 🙂

Leave a Comment