Categories
WordPress

How to check for a minimum level of PHP within a WordPress plugin

Oh my. It’s been a long time since I’ve felt such hate from users. What horrendous thing did I do? I change one of my plugins so that it now required PHP 7 to work, instead of 5.3.

You know PHP 7… which itself goes out of support in the next few months. PHP 7 also being the recommended minimum level of PHP for running WordPress.

Anyhow, I’ve written a short function which, when added to a plugin, will check for the current level and fail the activation if it doesn’t meet the requirements.

Simply add the following code to any plugin code…

<?php
function check_php_level() {
$php = '[[your minimum PHP level]]'; // Minimum PHP level required
/* translators: %1$s: required PHP version, %2$s: current PHP level */
$message = sprintf( __( 'The [[your plugin name]] plugin requires PHP version %1$s or greater but you are using version %2$s. The plugin has NOT been activated.', '[[your text-domain]]' ), $php, PHP_VERSION );
$title = __( 'Plugin Activation Error', '[[your text-domain]]' );
if ( version_compare( PHP_VERSION, $php, '<' ) ) {
wp_die( esc_html( $message ), esc_html( $title ) );
} else {
return;
}
}
register_activation_hook( __FILE__, 'check_php_level' );
view raw yourplugin.php hosted with ❤ by GitHub

Now replace all text that is surrounded by double brackets for an appropriate replacement – this includes the level of PHP you’re checking for, the plugin name and the text domain (for translations).

Hopefully, this is a short-term band-aid, as there are already plans to prevent plugins updates in future if the level of PHP is no longer supported – Trac tickets #43987 and #44350. Right now, these are planned for WordPress 5.0, which is due later in the year.

Photo by Henri L. on Unsplash

Talk to me!

This site uses Akismet to reduce spam. Learn how your comment data is processed.