Samuel Elh Blog

WordPress, bbPress, BuddyPress, JavaScript tutorials and snippets

Using version_compare to run WordPress plugin on minimal PHP requirements

As we know, WordPress can run in an environment with very minimal technical requirements, including an outdated PHP version of 5.2, which was EOL’d couple years ago, and can run as well with the latest PHP software.

As WordPress plugin/theme developers, we get support messages and notifications frequently from users encountering errors and bugs while trying to run our plugin or theme while the minimal technical requirements aren’t met. It is not their fault that they don’t upgrade their PHP software to the min required, but it is actually our fault, could be, just mentioning in the product descriptions or documentation the minimum requirements for the product, and not limiting the code to run only when those requirements are met..

PHP comes with a useful to compare versions, since PHP 4:

version_compare( $version1, $version2, $operator )

And to get the current PHP version you can use

PHP_VERSION

predefined constant.

Using version_compare to run WordPress plugin on the correct requirements

It all depends the style and way you’re coding it. Each PHP component or method or function has a first appear version, so as you develop a plugin or a theme, you know the minimum require PHP version for a perfect setup.

An example is, using namespaces to correctly organize and load your plugin components, the minimum required version for namespaces is 5.3. Also, a good example is anonymous functions, which are introduced in same version also.

It is always handy and a good experience to alert the admin of a custom error on the screen using admin notices API (admin_notices action hook), while an install can not run your plugin correctly.

Here’s a custom notice preview:

admin notice preview

Here’s an example class to compare versions:

/**
  * Compare PHP versions
  * Making sure this blog is running enough required PHP software for
  * our plugin
  */

Class VersionCompare
{
    public $hasRequiredPHP;
    protected $min, $operator;

    public function __construct( $minVersion = '5.3', $operator = '>=' )
    {
        $this->min = $minVersion;
        $this->operator = $operator;

        if ( version_compare(PHP_VERSION, $this->min, $operator) ) {
            $this->hasRequiredPHP = true;
        } else {
            add_action( "admin_notices", array( $this, "notice" ) );
        }
    }

    public function notice()
    {
        printf(
            '<div class="error notice is-dismissible"><p>Plugin Name requires PHP %s %s.</p></div>',
            $this->operator,
            $this->min
        );
    }
}

A simple usage is instantiating the class in a custom variable, with first parameter set the PHP version we’re targeting (falls back to 5.3), and an optional operator which falls back to >= for comparing for greater than or equal our target min. PHP version.

$VersionCompare = new VersionCompare('5.4');

Now

$VersionCompare->hasRequiredPHP

will be set to true if the user has met the targeted version with the specified operator. If not, then, let’s make sure the theme or plugin stops right there and add an elegant error message on the admin screen:

if ( !isset($VersionCompare->hasRequiredPHP) || !$VersionCompare->hasRequiredPHP ) {
    return; // no min server requirements, stop, no more code below will be executed
}

Here, the full class code and a basic usage:

if ( !class_exists('VersionCompare') ) :

/**
  * Compare PHP versions
  * Making sure this blog is running enough required PHP software for
  * our plugin
  */

Class VersionCompare
{
    public $hasRequiredPHP;
    protected $min, $operator;

    public function __construct( $minVersion = '5.3', $operator = '>=' )
    {
        $this->min = $minVersion;
        $this->operator = $operator;

        if ( version_compare(PHP_VERSION, $this->min, $operator) ) {
            $this->hasRequiredPHP = true;
        } else {
            add_action( "admin_notices", array( $this, "notice" ) );
        }
    }

    public function notice()
    {
        printf(
            '<div class="error notice is-dismissible"><p>Plugin Name requires PHP %s %s.</p></div>',
            $this->operator,
            $this->min
        );
    }
}

$VersionCompare = new VersionCompare(); 

if ( !isset($VersionCompare->hasRequiredPHP) || !$VersionCompare->hasRequiredPHP ) {
    return; // no min server requirements, stop it right there
}

endif;

Now it is quite reasonable to add all the previous code to the top of your plugin/theme main loader file, for plugins, add it to the file where you specify the plugin details and properties e.g Plugin Name, Plugin URI..

Here’s an example:

<?php namespace BMC;
/*
Plugin Name: bbPress Messages Compose
Plugin URI: https://github.com/elhardoum/bbpm-compose
Description: bbPress Messages Compose
Author: Samuel Elh
Version: 0.1
Author URI: https://samelh.com
*/

// prevent direct access
defined('ABSPATH') || exit('Direct access not allowed.' . PHP_EOL);

if ( !class_exists('VersionCompare') ) :

/**
  * Compare PHP versions
  * Making sure this blog is running enough required PHP software for
  * our plugin
  */

Class VersionCompare
{
    public $hasRequiredPHP;
    protected $min, $operator;

    public function __construct( $minVersion = '5.3', $operator = '>=' )
    {
        $this->min = $minVersion;
        $this->operator = $operator;

        if ( version_compare(PHP_VERSION, $this->min, $operator) ) {
            $this->hasRequiredPHP = true;
        } else {
            add_action( "admin_notices", array( $this, "notice" ) );
        }
    }

    public function notice()
    {
        printf(
            '<div class="error notice is-dismissible"><p>Plugin Name requires PHP %s %s.</p></div>',
            $this->operator,
            $this->min
        );
    }
}

$VersionCompare = new VersionCompare('5.3'); // namespaces

if ( !isset($VersionCompare->hasRequiredPHP) || !$VersionCompare->hasRequiredPHP ) {
    return; // no min server requirements, stop it right there
}

endif;

use \BMC\Includes\Plugin, \BMC\Includes\Admin;

class BMC
{
    /** Constants **/
    public $constants;

    public function init()
    {
        // define constants
        $this->defineConstants();
    }

    # rest of code ...

There are many other implementations of this, checking for desired other plugins versions, or comparing WordPress version itself (

get_bloginfo('version')

), for making sure.

The point is, stop executing your product code when no minimal requirements are met, so as to avoid any bugs, conflicts, or errors on the screen bugging visitors and attracting attacks from robots. Instead, give a heads up to site admin to upgrade their software, or drop the plugin.

Digital Ocean

Cheap Cloud SSD Hosting

Get a VPS now starting at $5/m, fast and perfect for WordPress and PHP applications

Sign Up with $10 Credit

1 Comment

  1. Thanks for this explanation 🙂

Leave a Reply

Your email address will not be published.

*

© 2017 Samuel Elh - Powered by WordPress, DigitalOcean & NameCheap

Theme by Anders NorenUp ↑

Subscribe to our mailing list

Sign up to receive updates about WordPress, free and premium plugins and themes in general and tips and tricks

* indicates required