duanke2503 2019-05-13 15:19
浏览 182
已采纳

检查WooCommerce是否处于活动状态以及使用的版本

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
    }
}
  • 写回答

1条回答 默认 最新

  • duanmo7075 2019-05-13 20:28
    关注

    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;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?