IRDN
IRDN

Reputation: 107

How to check if WooCommerce plugin is enabled?

I'm trying to check if WooCommerce plugin is active then add some options to the option panel. but this code doesn't work right.

can anyone tell me what is wrong?

 if( class_exists( 'WooCommerce' )) {//add options}

Upvotes: 3

Views: 5463

Answers (3)

AlexMinza
AlexMinza

Reputation: 95

The official recommendation is to add an action handler for woocommerce_loaded where to perform the initialization:

There are a few methods to achieve this. The first is to execute your code on the woocommerce_loaded action. This approach guarantees that WooCommerce and its functionalities are fully loaded and available for use. This is fired around the same time as the core plugins_loaded action.

add_action( 'woocommerce_loaded', 'prefix_woocommerce_loaded' );

function prefix_woocommerce_loaded() {
    // Custom code here. WooCommerce is active and all plugins have been loaded...
}

Reference: https://github.com/woocommerce/woocommerce/blob/trunk/docs/extension-development/check-if-woo-is-active.md

Upvotes: 1

mujuonly
mujuonly

Reputation: 11861

Alternatively, the function is_plugin_active method can be used to check if a plugin is active.

if ( is_plugin_active( 'woocommerce/woocommerce.php' ) ) {
    // woocommerce is active
} else {
    // woocommerce is not active
}

Another method documented in WooCommerce is the below option.

/**
 * Check if WooCommerce is activated
 */
if ( ! function_exists( 'is_woocommerce_activated' ) ) {
    function is_woocommerce_activated() {
        if ( class_exists( 'woocommerce' ) ) { return true; } else { return false; }
    }
}

Upvotes: 5

LoicTheAztec
LoicTheAztec

Reputation: 253804

Try the following instead:

if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
    // Yes, WooCommerce is enabled
} else {
    // WooCommerce is NOT enabled!
}

Upvotes: 9

Related Questions