Skip to content

Failing Gracefully if a Required Plugin is Not Installed

Posted in Plugin Development, and WP Plugins

Many times, plugins that we create are meant to extend or build on other plugins that already exist. For example, if you search “Gravity Forms”, you can find hundreds of other plugins that modify, extend, or otherwise change the capabilities of the base Gravity Forms plugin.

Whether these plugins are from the official Gravity Forms team or from third parties, they all share one thing in common: without Gravity Forms installed, they are at best useless and at worst, can cause errors within your site.

WordPress attempts to mitigate this by refusing to activate any plugins that throw a fatal PHP error, but relying on this is far from best practice. We’ll look today at how to let a plugin install fail gracefully, if a dependent plugin is not activated.

Ideally, this will take place in a few step process:

  • Check if dependency is installed and activated.
  • If it is, activate the plugin as usual.
  • If the dependency is not active, do the following:
    • Alert the user in an informative way, without throwing a PHP error
    • Deactivate the plugin to prevent any other issues.

We can do this with the register_activation_hook, which runs when a plugin is activated for the first time. The register_activation_hook takes two parameters, the file name for the plugin, and the function to run.

Let’s look at a sample activation hook checking for a dependency.

//function to run on activation
function installments_stripe_gf_activate() {
  
    if( !class_exists( 'GF_Stripe_Bootstrap' ) ) {
	
		 deactivate_plugins( plugin_basename( __FILE__ ) );
         wp_die( __( 'Please activate Gravity Forms + the official Stripe Plugin for Gravity Forms.', 'installments-for-stripe-gf' ), 'Plugin dependency check', array( 'back_link' => true ) );
        
    }
}

//sets up activation hook
register_activation_hook(__FILE__, 'installments_stripe_gf_activate');

Line 4 uses the class_exists php function to return false if the class passed as a parameter does not exist. Negating that result with ! allows us to run the code block to gracefully fail only if the code block does not exist. This requires us to know a class unique to the plugin we want to check for. We can also check for function_exists, if there is a unique function you would like to use instead of a class.

Line 6 uses WordPress’s deactivate_plugin function to deactivate this plugin since it is lacking the required dependency, and line 7 sends the user to a custom message explaining why the activation failed, with a link to take them back to the plugin page.

By adding this simple if statement to your register_activation_hook, you can prevent errors, frustrated users, and greatly improve your third party integration.