bannerbannerbannerbannerbanner
Jova wiki   tid   Login/Logout

Navigation





Search the wiki
»

PoweredBy

Tricks

More tricks

This is taken from wp-hackers


Scott Merrill wrote:
> Bill Smith wrote:
>>1) I'm working on a small plugin that requires an additional database
>>table. Currently I'm using a query like
>>
>>SHOW TABLES LIKE 'wp_mytable'
> 
> Here's what I do in my subscribe2 plugin, which uses a custom table:
> ///////////////////////
> function s2_install() {
> // include upgrade-functions for maybe_create_table;
> if (! function_exists('maybe_create_table')) {
>         require_once(ABSPATH . '/wp-admin/upgrade-functions.php');
> }
maybe_create_table() also uses SHOW TABLES, which is fine, but doesn't avoid that query if that's the intent.

Here's what I do:

class MyPlugin {
  $table_version = 1;
  function MyPlugin() {
   $this->settings = get_settings('MyPlugin');
   if($this->settings['table_version'] < $this->$table_version)
    $this->make_tables();
   //These also go here:
   // add_action('admin_menu', array(&$this, 'admin_menu'));
  }
  function make_tables() {
   global $table_prefix;
   if(!require_once(ABSPATH . 'wp-admin/upgrade-functions.php')) {
    die('Foolish plugin has added its own maybe_upgrade* functions');
   }
   $qry = "CREATE TABLE {$table_prefix}mytable (
    mytable_id BIGINT(11) NOT NULL AUTO_INCREMENT,
    PRIMARY KEY  (mytable_id)
    );
    ";
   dbDelta($qry);
   $this->settings['table_version'] = $this->table_version;
   update_option('MyPlugin', $this->settings);
  }
}
$myplugin = new MyPlugin();
What benefit has all this? If you change the table structure in an upgrade (add a field, change a field type, add an enum value, etc.), you simply increment the $table_version and the plugin will automatically upgrade the table. Plus it's one less database hit if the options info is already cached.

Jova wiki is © Jovall