ガイド/WooCommerceの通貨換算

WooCommerceの通貨換算

WooCommerceの通貨換算. コード、キャッシュ、鮮度メタデータを含む実践ガイドです。

ERexchangerate.dev·Sep 20, 2026·7分で読めます

認証情報を公開せず、出典と観測時刻を保持してサーバー側で実装します。

要点
APIキーはサーバーだけに保存する。
通貨コードと金額を検証する。
成功したレスポンスをキャッシュする。
出典と観測時刻を表示する。

手順 1

コード例copy
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

サーバー側で実行し、入力を検証してレスポンスのメタデータを保存します。

コード例copy
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キーはサーバーだけに保存する。
  • 通貨コードと金額を検証する。
  • 成功したレスポンスをキャッシュする。
  • 出典と観測時刻を表示する。
ガイド
表示される値は参考レートであり、決済価格ではありません。
ER
exchangerate.dev
通貨データを扱う開発者向けの実践ガイド。

関連記事

ガイド開発者向け通貨換算API読む ガイドShopifyの通貨換算読む ガイドExchange rates for SaaS billing読む