You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复WordPress中Call to undefined function get_woocommerce_currency()错误

解决WooCommerce自定义配送插件中get_woocommerce_currency()未定义错误及货币条件激活方案

我来帮你分析这个问题的原因,以及给出具体的修复和功能实现方案:

错误原因

你遇到的Call to undefined function get_woocommerce_currency()致命错误,核心问题是代码执行时机太早:

  • get_woocommerce_currency()是WooCommerce专属的核心函数,它定义在WooCommerce的includes/wc-core-functions.php文件中,并非WordPress核心的wp-includes/option.php里,所以手动引入option.php完全起不到作用。
  • 当你的代码直接在插件主文件顶部调用这个函数时,WooCommerce还没完成加载流程,系统自然找不到这个未被定义的函数。

修复与功能实现方案

1. 实现「仅USD时启用自定义配送方式」

所有依赖WooCommerce的逻辑,都要挂在WooCommerce专属的动作钩子上执行,确保WooCommerce完全加载后再调用相关函数。推荐使用woocommerce_loaded钩子(WooCommerce加载完成后触发),代码示例如下:

// 等待WooCommerce加载完成后执行货币检测
add_action( 'woocommerce_loaded', 'my_custom_shipping_currency_check' );

function my_custom_shipping_currency_check() {
    // 若当前货币不是USD,禁用自定义配送方式
    if ( 'USD' !== get_woocommerce_currency() ) {
        add_filter( 'woocommerce_shipping_methods', 'disable_my_custom_shipping_method' );
    }
}

function disable_my_custom_shipping_method( $shipping_methods ) {
    // 替换成你自定义配送方式的注册ID
    $custom_shipping_id = 'my_custom_shipping_service';
    if ( isset( $shipping_methods[$custom_shipping_id] ) ) {
        unset( $shipping_methods[$custom_shipping_id] );
    }
    return $shipping_methods;
}

2. 实现「仅USD时激活整个插件」

如果你的需求是整个插件只在USD货币环境下才生效,可以在插件初始化阶段添加检测逻辑,同时给后台用户提示:

// 先检查WooCommerce是否已激活
if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
    // 挂在WooCommerce初始化钩子上执行货币检测
    add_action( 'woocommerce_init', 'my_plugin_restrict_to_usd' );
}

function my_plugin_restrict_to_usd() {
    if ( 'USD' !== get_woocommerce_currency() ) {
        // 注销插件所有核心功能钩子(替换成你插件的实际初始化钩子)
        remove_action( 'woocommerce_shipping_init', 'my_custom_shipping_init' );
        
        // 在后台显示错误提示
        add_action( 'admin_notices', 'my_plugin_currency_notice' );
    }
}

function my_plugin_currency_notice() {
    echo '<div class="notice notice-error is-dismissible">
            <p>自定义配送插件仅在网站使用USD货币时可用,请前往「WooCommerce → 设置 → 常规」切换基准货币为USD以启用该插件。</p>
          </div>';
}

关键注意事项

  • 永远不要在插件主文件的全局作用域直接调用WooCommerce函数,必须通过动作钩子延迟执行,确保WooCommerce加载完成。
  • 若你还未注册自定义配送方式,需要先通过woocommerce_shipping_init钩子完成注册,再用上述逻辑根据货币条件动态移除。
  • 测试时可在WooCommerce设置中切换基准货币,验证功能是否正常生效。

内容的提问来源于stack exchange,提问作者Old Ceylon Mudliar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:48:08