23 April, 2013 — Snippets, WordPress

Check WordPress Version

You can’t assume everyone is running the latest version of WordPress. According to WordPress stats there are currently 6 different versions of WordPress people are using most, and I’m sure there will be many more they don’t know about!

WordPress Version from WordPress.org

WordPress Version from WordPress.org

Using version_compare

If you want your code to be backwards compatible, you can do the following code with conditionals by using:

if(!function_exists('is_version')){
    function is_version($version = '3.5', $compare = '>=') {
        global $wp_version;

        if(version_compare($wp_version, $version, $compare)){
            return false;
        }
        return true;
    }
}

The code above will check that the current version of WordPress is compatible with the code you are trying to run. You can call the above function as follows:

if(is_version("3.4", ">="){
    // Code run here will only run on WordPress 3.4 and above.
}

You can read about version compare at php.net.

Use function_exists

Another easy way to find the version is to check for a function that was introduced after a certain release. For instance, post formats were introduced in 3.1. So to see if the installation is 3.1 or higher you could use something like:

if(function_exists('has_post_format')){
    // 3.1 specific code
}

Photo Credit: WordPress