Reputation: 2412
I need to check if WooCommerce is active and check its version number to make it work differently for new and old versions.
I found that WC_VERSION
stores version number, so if it exists, it also means that WooCommerce is active. The problem is that it can return anything only after plugins are loaded. I would like to check version and then use outside woocommerce_ver_check function
in general scope. Can I do it without global variables?
I want to do something like this, but woocommerce_ver_check()
is always null, because it executes after WooCommerce is loaded, unlike the rest of the code which is not assigned to any hook:
// Check WooCommerce version.
add_action('plugins_loaded', 'woocommerce_ver_check');
function woocommerce_ver_check() {
if (defined('WC_VERSION')) return WC_VERSION;
}
// Only if WooCommerce is active.
if (! woocommerce_ver_check() == null ) {
if ( version_compare( WC_VERSION, '3.0', '>=' ) ) {
// new version code
} else {
// old version code
}
}
Upvotes: 3
Views: 4648
Reputation: 253919
You can also try to use the following (that is used for WooCommerce third party plugins):
if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
if ( version_compare( WC_VERSION, '3.0', '<' ) ) {
// Old version code (example)
$product_id = $cart_item['data']->id
} else {
// New version code (example)
$product_id = $cart_item['data']->get_id();
}
}
For new WooCommerce 3 CRUD Object methods you can also use method_exists()
like for example:
$order_id = method_exists( $order, 'get_id' ) ? $order->get_id() : $order->id;
Upvotes: 1