When I deactive WooCommerce Plugin, I want to take a action in My plugin

I have a WordPress plugin which is dependent on WooCommerce. When a user uninstalls or deactivates the WooCommerce plugin, in this time, I mean when WooCommerce plugin register_deactivation_hook, I want to take a notice in my active current plugin. How can I do this? please help.

Topic deactivation plugin-development Wordpress

Category Web


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...

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.