error-handlingconditional-statementswordpresssystem-requirements

Proper way to check system requirements for a WordPress plugin


I am curious about the proper way to stop a user from activating my plugin if their system does not meet certain requirements. Doing the checks is easy and I don't need any help with that, I am more curious how to tell WordPress to exit and display an error message.

Currently I have tried both exit($error_message) and die($error_message) in the activation hook method. While my message is displayed and the plugin is not activated, a message saying Fatal Error is also displayed (see image below).

enter image description here

Does anyone know of a better way, that would display my message in a proper error box without displaying Fatal error, it just looks really bad for new users to see that.

Thanks for any help in advance.


Solution

  • This is a little undocumented, as you might have noticed. Instead of die(), do it like this:

    $plugin = dirname(__FILE__) . '/functions.php';
    deactivate_plugins($plugin);
    wp_die('<p>The <strong>X</strong> plugin requires version WordPress 2.8 or greater.</p>','Plugin Activation Error',array('response'=>200,'back_link'=>TRUE));
    

    The lines above wp_die() are to deactivate this plugin. Note that we use functions.php in this case because that's where I have my Plugin Name meta data comment declaration -- and if you use a different file, then change the code above. Note that the path is very specific for a match. So, if you want to see what your path would normally be, use print_r(get_option('active_plugins'));die(); to dump that out so that you know what path you need. Since I had a plugin_code.php where the rest of my plugin code was, and since it was in the same directory as functions.php, I merely had to do dirname(__FILE__) for the proper path.

    Note that the end of the wp_die() statement is important because it provides a backlink and prevents an error 500 (which is the default Apache code for wp_die()).