Skip to content

Instantly share code, notes, and snippets.

@joshuadavidnelson
Last active April 18, 2017 03:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshuadavidnelson/152a4e41df73f34804284c8aa0b2faa9 to your computer and use it in GitHub Desktop.
Save joshuadavidnelson/152a4e41df73f34804284c8aa0b2faa9 to your computer and use it in GitHub Desktop.
<?php
/**
* Example code taken from: https://pento.net/2014/02/18/dont-let-your-plugin-be-activated-on-incompatible-sites/
*/
// In this example, only allow activation on WordPress 3.7 or higherclass
MyPlugin {
function __construct() {
add_action( 'admin_init', array( $this, 'check_version' ) );
// Don't run anything else in the plugin, if we're on an incompatible WordPress version
if ( ! self::compatible_version() ) {
return;
}
}
// The primary sanity check, automatically disable the plugin on activation if it doesn't// meet minimum requirements.static
function activation_check() {
if ( ! self::compatible_version() ) {
deactivate_plugins( plugin_basename( __FILE__ ) );
wp_die( __( 'My Plugin requires WordPress 3.7 or higher!', 'my-plugin' ) );
}
}
// The backup sanity check, in case the plugin is activated in a weird way,
// or the versions change after activation.
function check_version() {
if ( ! self::compatible_version() ) {
if ( is_plugin_active( plugin_basename( __FILE__ ) ) ) {
deactivate_plugins( plugin_basename( __FILE__ ) );
add_action( 'admin_notices', array( $this, 'disabled_notice' ) );
if ( isset( $_GET['activate'] ) ) {
unset( $_GET['activate'] );
}
}
}
}
function disabled_notice() {
echo '<strong>' . esc_html__( 'My Plugin requires WordPress 3.7 or higher!', 'my-plugin' ) . '</strong>';
}
static function compatible_version() {
if ( version_compare( $GLOBALS['wp_version'], '3.7', '<' ) ) {
return false;
}
// Add sanity checks for other version requirements here
return true;
}
}
global $myplugin;
$myplugin = new MyPlugin();
register_activation_hook( __FILE__, array( 'MyPlugin', 'activation_check' ) );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment