There’s two ways to do this, you can either check for the main plugin file or you can check for the WooCommerce class. When I make a plugin dependent on some other plugin I usually check for the plugin file, but for WooCommerce I check for the WooCommerce class.
<?php
function yourplugin_init() {
if( !function_exists( 'is_plugin_inactive' ) ) :
require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
endif;
//COMMON WOOCOMMERCE METHOD
if( !class_exists( 'WooCommerce' ) ) :
//ALTERNATIVE METHOD
//if( is_plugin_inactive( 'woocommerce/woocommerce.php' ) ) :
add_action( 'admin_init', 'yourplugin_deactivate' );
add_action( 'admin_notices', 'yourplugin_admin_notice' );
function yourplugin_deactivate() {
deactivate_plugins( plugin_basename( __FILE__ ) );
}
function yourplugin_admin_notice() {
echo '<div class="error"><p><strong>WooCommerce</strong> must be installed and activated to use this YOURPLUGIN.</p></div>';
if( isset( $_GET['activate'] ) ) unset( $_GET['activate'] );
}
endif;
}
add_action( 'plugins_loaded', 'yourplugin_init' );
?>
First, put the above code in your primary plugin file before any of the custom functionality you’re adding.
We create a function that we run on plugins_loaded
; it checks if the WP is_plugin_inactive
function executes, if not, it loads the WP plugin file.
Next we check if a) the WooCommerce
class does NOT exist or b) the alternative method which I’ve commented out, we check if the WooCommerce plugin is INACTIVE using the plugin’s main PHP file (ie. woocommerce/woocommerce.php
).
Now, IF we’ve established that WooCommerce isn’t active (using one of the two methods above) we hook into two separate actions.
admin_init
admin_notices
Then we have two functions yourplugin_deactivate()
and yourplugin_admin_notice()
which are pretty self explanatory. We deactivate the your plugin and then we post a notice at the top of the admin screen telling the user what we’ve done and why.
And there you go…