我知道这是一个古老的问题,但对于那些寻求好的解决方案的人来说,Gary Pendergast有一条很好的路线,涵盖了其他答案中提到的一些基础(参见他的帖子here, 我已经更新了下面的代码来检查PHP版本,但您几乎可以将其用于任何检查):
// 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 PHP 5.1 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 PHP 5.1 or higher!\', \'my-plugin\' ) . \'</strong>\';
}
static function compatible_version() {
if ( version_compare(PHP_VERSION, \'5.1\', \'<\') ) {
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\' ) );
我还将上述代码保存在
gist.