While I was working on a WordPresss plugin recently, I needed to implement a version check. The plugin required WordPress 2.7 or greater, and it made use of several functions available only in PHP 5 and up (such as SimpleXML). It seemed like there should be some sort of version check, so if an installation did not meet the minimum requirements it would exit with an error.
I ended up writing this function:
function my_plugin_activated() {
global $wp_version;
if (version_compare($wp_version, '2.7', '< ')) {
exit("This plugin requires WordPress 2.7 or greater.");
}
if (version_compare(PHP_VERSION, '5.0.0', '<')) {
exit("This plugin requires PHP 5 or greater.");
}
}
The useful, but less than publicized version_compare() function is the active ingredient of my version check. It compares two standard version numbers, such as those used by PHP and WordPress for their software releases, using the operator you specify.
The syntax is:
version_compare ( $version1 , $version2, $operator )
All three arguments are strings, the first two in the form of 1.7.1 or 1.7.0-beta. The third argument is an operator, such as =
or <
. So the statement version_compare(PHP_VERSION, '5.0.0', '<')
would return true if PHP_VERSION
, a contant that PHP automatically fills with its version number, is less than 5.0.0. It would return false otherwise.
Since I was writing a WordPress, plugin, I hooked into the plugin activation action like so:
register_activation_hook(__FILE__, 'my_plugin_activated');
And that’s all. A simple version check that will stop the plugin from executing and output an error when the PHP version and WordPress version aren’t up to the requirements.