指南指南

WooCommerce 货币转换

WooCommerce 货币转换. 包含代码、缓存和数据新鲜度的实用指南。

2026年9月20日 · 阅读约 7 分钟

在服务器端实现,不泄露凭据,并保留数据来源与观测时间。

  • 仅在服务器保存 API 密钥。
  • 验证货币代码和金额。
  • 缓存成功响应。
  • 显示来源和观测时间。

步骤 1

代码示例
function exr_convert_for_display($amount, $from, $to) {    $from = strtoupper(sanitize_text_field($from));    $to = strtoupper(sanitize_text_field($to));    $cache_key = 'exr_' . md5($from . '_' . $to);    $rate = get_transient($cache_key);    if ($rate === false) {        $url = sprintf('https://api.exchangerate.dev/v1/convert/%s/%s/1', $from, $to);        $response = wp_remote_get($url, array(            'timeout' => 5,            'headers' => array('Authorization' => 'Bearer ' . EXCHANGERATE_API_KEY),        ));        if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) {            return null;        }        $body = json_decode(wp_remote_retrieve_body($response), true);        $rate = isset($body['rate']) ? (string) $body['rate'] : null;        if ($rate === null) return null;        set_transient($cache_key, $rate, MINUTE_IN_SECONDS);    }    return (float) $amount * (float) $rate;}

步骤 2

请在服务器端执行,验证输入,并保留响应元数据。

代码示例
add_filter('woocommerce_get_price_html', function ($html, $product) {    $estimate = exr_convert_for_display((float) $product->get_price(), 'USD', 'EUR');    if ($estimate === null) return $html;    return $html . '<small class="fx-estimate">Estimated ' .        wp_kses_post(wc_price($estimate, array('currency' => 'EUR'))) . '</small>';}, 10, 2);

步骤 3

  • 仅在服务器保存 API 密钥。
  • 验证货币代码和金额。
  • 缓存成功响应。
  • 显示来源和观测时间。
指南

这些汇率仅供参考,并非结算价格。

常见问题

WooCommerce 货币转换

可通过文档化 JSON 接口在应用中集成货币转换和指示性汇率。

继续阅读

从免费API密钥开始

免费套餐每月提供5,000次请求。无需信用卡。

获取免费密钥