คู่มือ/การแปลงสกุลเงินสำหรับ WooCommerce

การแปลงสกุลเงินสำหรับ WooCommerce

การแปลงสกุลเงินสำหรับ WooCommerce. คู่มือพร้อมโค้ด การแคช และข้อมูลความสดใหม่

ERexchangerate.dev·Sep 20, 2026·อ่าน 7 นาที

ใช้งานบนเซิร์ฟเวอร์โดยไม่เปิดเผยข้อมูลลับ และเก็บแหล่งที่มากับเวลาสังเกต

ประเด็นสำคัญ
เก็บ API key ไว้บนเซิร์ฟเวอร์
ตรวจสอบรหัสสกุลเงินและจำนวนเงิน
แคชผลลัพธ์ที่สำเร็จ
แสดงแหล่งที่มาและเวลาสังเกต

ขั้นตอนที่ 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 key ไว้บนเซิร์ฟเวอร์
  • ตรวจสอบรหัสสกุลเงินและจำนวนเงิน
  • แคชผลลัพธ์ที่สำเร็จ
  • แสดงแหล่งที่มาและเวลาสังเกต
คู่มือ
อัตราเหล่านี้ใช้เพื่ออ้างอิง ไม่ใช่ราคาชำระจริง
ER
exchangerate.dev
คู่มือสำหรับนักพัฒนาที่ใช้ข้อมูลสกุลเงิน

อ่านต่อ

คู่มือAPI แปลงสกุลเงินสำหรับนักพัฒนาอ่าน คู่มือการแปลงสกุลเงินสำหรับ Shopifyอ่าน คู่มือExchange rates for SaaS billingอ่าน