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

如何向WooCommerce REST API暴露辅币并解决接口返回价格为0的问题

问题原因
  • WooCommerce Multilingual默认未将辅币价格数据适配到WooCommerce原生REST API的返回逻辑中,你看到的0值是接口未匹配到对应价格时返回的默认占位值,和后台价格配置无关
  • WPML多货币的价格匹配逻辑默认仅在前端页面渲染时触发,会根据当前访客的语言、地区自动加载对应货币价格,REST API调用时不会自动触发该逻辑,未加载辅币价格配置就会返回0
  • 如果你查询的是可变商品的变体数据,也可以先确认后台是否单独给该变体配置了对应辅币的价格,未单独保存变体辅币价格的场景下也会返回默认0值
辅币价格暴露到REST API的实现方法

可以通过WooCommerce的REST接口钩子自定义返回字段,直接读取WooCommerce Multilingual存储的辅币价格插入返回结果即可,代码可以添加到主题functions.php文件或者自定义功能插件中:

// 给简单商品、可变商品REST返回结果增加多货币价格
add_filter('woocommerce_rest_prepare_product_object', 'wcml_add_multi_currency_to_rest_api', 10, 3);
// 给可变商品变体REST返回结果增加多货币价格
add_filter('woocommerce_rest_prepare_product_variation_object', 'wcml_add_multi_currency_to_rest_api', 10, 3);

function wcml_add_multi_currency_to_rest_api($response, $post, $request) {
    global $woocommerce_wpml;
    // 判WCML多货币功能是否启用
    if (!is_object($woocommerce_wpml) || empty($woocommerce_wpml->multi_currency)) {
        return $response;
    }
    $product = wc_get_product($post->ID);
    $enabled_currencies = $woocommerce_wpml->multi_currency->get_currencies();
    $currency_prices = [];
    // 循环读取所有启用货币的价格
    foreach ($enabled_currencies as $code => $currency_info) {
        $price_data = $woocommerce_wpml->multi_currency->prices->get_product_price_in_currency($product, $code);
        $currency_prices[$code] = [
            'regular_price' => wc_format_decimal($price_data['regular_price'], wc_get_price_decimals()),
            'sale_price' => wc_format_decimal($price_data['sale_price'], wc_get_price_decimals()),
            'current_price' => wc_format_decimal($price_data['price'], wc_get_price_decimals())
        ];
    }
    $response->data['multi_currency_prices'] = $currency_prices;
    return $response;
}

添加代码后再调用REST接口,所有已配置的辅币价格都会自动包含在返回结果中,不会再出现价格为0的问题。

内容的提问来源于stack exchange,提问作者Jerry

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 13:27:03