WordPress Plugin – Database integration

The next step with the plugin is to add some database integration so the plugin options can be stored in the WordPress database. This is really simple as the API provides funtions for this in the form of the functions add_option, get_option, update_option and delete_option.

To ensure that the database is populated with some defaults, a hook can be added to do this:

[code lang=”php”]register_activation_hook(__FILE__, array(&$this, ‘Activate’));[/code]

[code lang=”php”] /**
* Activation function – adds database settings
*
* @return void
*/
function Activate() {
add_option(‘WP_Thumbshot_Preview_Mode’, ‘free’, ”, ‘yes’);
add_option(‘WP_Thumbshot_Preview_Cid’, ”, ”, ‘yes’);
add_option(‘WP_Thumbshot_Preview_Width’, ‘160’, ”, ‘yes’);
add_option(‘WP_Thumbshot_Preview_Height’, ‘120’, ”, ‘yes’);
}[/code]

This will be triggered when a user installs the plugin and the default options will be saved to the WordPress options database.

I have also added a deactivation hook to clean up the options from the database when the plugin is deactivated:

[code lang=”php”]register_deactivation_hook(__FILE__, array(&$this, ‘Deactivate’));[/code]

[code lang=”php”] /**
* Deactivation function – removes database settings
*
* @return void
*/
function Deactivate() {
delete_option(‘WP_Thumbshot_Preview_Mode’);
delete_option(‘WP_Thumbshot_Preview_Cid’);
delete_option(‘WP_Thumbshot_Preview_Width’);
delete_option(‘WP_Thumbshot_Preview_Height’);
}[/code]

The default options are set to use the free version of Thumbshots, so the plugin instantly works on activation without any changes to the default settings. To complete the database integration I have also added a function to get the default options from the database when the plugin is loaded (this function is run from the constructor):

[code lang=”php”] /**
* Populate settings from WP
*
* @return void
*/
function Populate_Settings() {
// Usage mode (defaults to free if database settings are missing)
if (($mode = get_option(‘WP_Thumbshot_Preview_Mode’)) !== false) {
$this->mode = $mode;
}
// Thumbshots cid for paid mode
if (($cid = get_option(‘WP_Thumbshot_Preview_Cid’)) !== false) {
$this->cid = $cid;
}
// Image width for paid mode
if (($width = get_option(‘WP_Thumbshot_Preview_Width’)) !== false) {
$this->width = $width;
}
// Image height for paid mode
if (($height = get_option(‘WP_Thumbshot_Preview_Height’)) !== false) {
$this->height = $height;
}
}[/code]

Note: The functions listed here are used as part of the object defined in my previous post.

Share

Leave a Reply