0

I have a simple if statement:

if (class_exists('Woocommerce')) {
    echo 'yes';
 } else {
    echo 'no';
}

This works fine when using it in a theme file (functions.php for example). But when I'm using it on a plugin (plugins/myplugin/myplugin.php) it doesn't work at all. How can I check if the plugin exists/is-active within my plugin to enable/disable some features? Am I missing something?

2 Answers 2

4

Woo Commerce provides code to check to see if WooCommerce is installed :


/**
 * Check if WooCommerce is active
 **/
if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
    // Put your plugin code here
}

If no idea where WooCommerece install then :


    $all_plugins = get_plugins();
    $active_plugins = get_option( "active_plugins" );

    foreach ( $all_plugins as $plugin_path => $value ) {

        if( basename( $plugin_path, ".php" ) == 'woocommerce') {
            if( in_array( $plugin_path, $active_plugins ) ) {
                return true;
            }else {
                return false;
            }
        }
    }

3
  • I wish I could have a power to downvote external sites.... what this code say is that if you install WC under a different directory it is not WC anymore :( Nov 1, 2016 at 10:07
  • @Mark Kaplun. I have updated the code. Nov 1, 2016 at 10:15
  • +1 for the effort, but this is really something you should do only if you have no other alternative. Nov 1, 2016 at 10:20
0

The best way is to run your code at actions triggered by the other plugin. If it has some initialization action than it is a perfect solution.

Otherwise this kind of check should better be done on the core wp_loaded hook and for sure not before plugins_loaded hook. Running it directly without any dependence on hook will just never work reliably.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.