检查 WooCommerce 是否处于活动状态以及使用的版本
Checking if WooCommerce is active and what version is used
我需要检查 WooCommerce 是否处于活动状态并检查其版本号以使其对新旧版本的工作方式有所不同。
我发现 WC_VERSION
存储版本号,所以如果它存在,也意味着 WooCommerce 处于活动状态。问题是只有在加载插件后它才能 return 任何东西。我想检查版本,然后在一般范围内使用外部 woocommerce_ver_check function
。我可以不用全局变量吗?
我想做这样的事情,但 woocommerce_ver_check()
始终为 null,因为它在加载 WooCommerce 后执行,这与未分配给任何挂钩的其余代码不同:
// 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
}
}
您也可以尝试使用以下(用于 WooCommerce 第三方插件):
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();
}
}
对于新的 WooCommerce 3 CRUD 对象方法,您还可以使用 method_exists()
,例如:
$order_id = method_exists( $order, 'get_id' ) ? $order->get_id() : $order->id;
我需要检查 WooCommerce 是否处于活动状态并检查其版本号以使其对新旧版本的工作方式有所不同。
我发现 WC_VERSION
存储版本号,所以如果它存在,也意味着 WooCommerce 处于活动状态。问题是只有在加载插件后它才能 return 任何东西。我想检查版本,然后在一般范围内使用外部 woocommerce_ver_check function
。我可以不用全局变量吗?
我想做这样的事情,但 woocommerce_ver_check()
始终为 null,因为它在加载 WooCommerce 后执行,这与未分配给任何挂钩的其余代码不同:
// 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
}
}
您也可以尝试使用以下(用于 WooCommerce 第三方插件):
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();
}
}
对于新的 WooCommerce 3 CRUD 对象方法,您还可以使用 method_exists()
,例如:
$order_id = method_exists( $order, 'get_id' ) ? $order->get_id() : $order->id;