Wordpress - How to check if a plugin (WooCommerce) is active?
Your edit got me to this idea, there indeed is no function called »woocommerce«, there is a class »WooCommerce
« though. One thing to be aware of is, that the check has to late enough, so that plug-ins are actually initialized, otherwise - obviously - the class won't exists and the check returns false
. So your check should look like this:
if ( class_exists( 'WooCommerce' ) ) {
// some code
} else {
/ more code
}
On the WooCommerce documentation page »Creating a plugin for WooCommerce« I have found this:
/**
* Check if WooCommerce is active
**/
if (
in_array(
'woocommerce/woocommerce.php',
apply_filters( 'active_plugins', get_option( 'active_plugins' ) )
)
) {
// Put your plugin code here
}
Personally I think it is not nearly as reliable as checking for the class. For obvious reasons, what if the folder/file name is different, but should work just fine too. Besides if you do it like this, then there is an API function you can use, fittingly named is_plugin_active()
. But because it is normally only available on admin pages, you have to make it available by including wp-admin/includes/plugin.php
, where the function resides. Using it the check would look like this:
include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
if ( is_plugin_active( 'woocommerce/woocommerce.php' ) ) {
// some code
} else {
/ more code
}
Many of the official WooCommerce plugins solve this by checking for the WC_VERSION
constant, which WooCommerce defines, once all plugins have loaded. Simplified code:
add_action('plugins_loaded', 'check_for_woocommerce');
function check_for_woocommerce() {
if (!defined('WC_VERSION')) {
// no woocommerce :(
} else {
var_dump("WooCommerce installed in version", WC_VERSION);
}
}
The added bonus is that you can use PHP's version_compare()
to further check if a new enough version of WooCommerce is installed (if you code requires specific capabilities), since the WC_VERSION constant is suitable for this.
To improve on the answers given, we're using this:
$all_plugins = apply_filters('active_plugins', get_option('active_plugins'));
if (stripos(implode($all_plugins), 'woocommerce.php')) {
// Put your plugin code here
}
This prevents two problems:
- WooCommerce being installed in a non-standard directory - in which case
if ( in_array( 'woocommerce/woocommerce.php', apply_filters(...
doesn't work. - This check being invoked before WooCommerce is loaded - in which case
if ( class_exists( 'WooCommerce' ) ) { .. }
doesn't work.