If you’re doing any kind of plugin development for WordPress, then you’re likely going to be releasing future updates to said plugin. In doing so, it’s always wise to track the version number for debugging purposes.
Here’s how…
[cc lang=”php”]
if (!defined(‘PLUGIN_VERSION’)) {
define(‘PLUGIN_VERSION’, ‘myplugin_version’);
}
if (!defined(‘PLUGIN_VERSION_NUM’)) {
define(‘PLUGIN_VERSION_NUM’, ‘1.0’);
}
add_option(PLUGIN_VERSION, PLUGIN_VERSION_NUM);
[/cc]
Easy enough.
Darren says
Great tip Tom,
But it’s better when doing this to namespace it so the potential for conflicts with other plugins doing the same thing won’t conflict (and you could end up with other plugin version info in your database).
For example if your plugin is named “My Awesome Plugin” you could use the initials “MYA” to prefix the example you gave here and give less chance of a collision with other plugins. Something like:
if (!defined('MYA_PLUGIN_VERSION')) {
define('MYA_PLUGIN_VERSION', 'myplugin_version');
}
if (!defined('MYA_PLUGIN_VERSION_NUM')) {
define('MYA_PLUGIN_VERSION_NUM', '1.0');
}
add_option(PLUGIN_VERSION, PLUGIN_VERSION_NUM);
Darren says
Dang it. can’t edit lol. the add_option should be:
add_option(MYA_PLUGIN_VERSION, MYA_PLUGIN_VERSION_NUM).
And I’m really good with abbreviations aren’t I? Probably would go with MAP. It’s late. I’m tired. 😉
Darren says
Oh and it should be added that this is really good practices for plugin authors because it also helps if a future update of your plugin requires changes to the way things worked on the database or other features in your plugin. By comparing previous versions with the new version you can execute an “upgrade” script to work behind the scenes.
Eg.
if (!defined('MYA_PLUGIN_VERSION')) {
define('MYA_PLUGIN_VERSION', 'myplugin_version');
}
if (!defined('MYA_PLUGIN_VERSION_NUM')) {
define('MYA_PLUGIN_VERSION_NUM', '1.2');
}
add_action('plugins_loaded', 'check_for_upgrade');
function check_for_upgrade() {
$old_version = get_option(MYA_PLUGIN_VERSION);
if ( empty($old_version) ) return; //this is a vanilla install, no upgrade needed.
if ( $old_version < MYA_PLUGIN_VERSION_NUM ) {
//execute version upgrade script here...
}
}
Tom McFarlin says
Darren,
Such good stuff – thanks for posting this!
Darren says
Thanks Tom,
Just realize one more thing should be added at the bottom of the script.
where we have:
if ( $old_version < MYA_PLUGIN_VERSION_NUM ) { //execute version upgrade script here... }
We need to add right after:
update_option(MYA_PLUGIN_VERSION, MYA_PLUGIN_VERSION_NUM);
That way, the version number in the database is updated, or could run into problems. I really need to not post code late at night!
BTW, if you want to post any of this in a separate post go right ahead!