PHP Version_Compare()

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.

  • http://ineeddiscipline.com/2008/07/04/19-blog-review-networks/ Dean Saliba

    This is very interesting. I am going to hate it when all plugins start insisting on PHP 5 as I have a couple of scripts (nothing to do with my blogs) that are no longer updated that will not work on PHP 5. :(

  • http://austinpassy.com The Frosty

    This came in handy! But, I modified it a bit for the familiarity of WordPress use:

    function is_version( $version = ‘3.0’ ) {
    global $wp_version;

    if ( version_compare( $wp_version, $version, ‘<' ) ) {
    return false;
    }
    return true;
    }

  • http://vimaxdetox.info Vimax Detox

    Greetings from Ohio! I’m bored to tears at work so I decided to browse your site on my iphone during lunch break. I really like the information you present here and can’t wait to take a look when I
    get home. I’m amazed at how quick your blog loaded on my phone .. I’m not even using WIFI, just 3G .
    . Anyhow, very good blog!