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

如何手动编写代码实现按钮切换两种货币展示Shopify商品价格

Shopify自定义汇率基准多货币功能实现方案

你之前的思路偏差核心在于没有理清Liquid和JS的执行顺序:Liquid运行在Shopify服务端,页面渲染完成发送到用户浏览器后就不会再执行,所以确实无法通过前端JS触发Liquid重新计算价格,正确的实现思路是把需要的基础数据提前通过Liquid注入到前端,所有动态切换逻辑完全在前端实现即可,具体步骤如下:

1. 服务端准备基础数据(Liquid实现)

  • 首先将你自定义的汇率表通过Liquid注入到前端全局变量,你可以直接硬编码到主题代码,也可以提前将汇率存在Shopify店铺/商品元字段中动态读取,示例代码添加到theme.liquid的<head>标签内即可:
<script>
// 自定义汇率表,基准为店铺默认货币
window.customExchangeRates = {
  '{{ shop.currency }}': 1,
  'EUR': 0.93,
  'CNY': 7.22,
  'GBP': 0.79,
  // 按需添加其他货币和对应自定义汇率
}
// 读取用户之前选择的货币,无记录则用店铺默认货币
window.selectedCurrency = localStorage.getItem('user_selected_currency') || '{{ shop.currency }}'
</script>
  • 所有页面的价格元素输出时都带上原始价格(店铺默认货币的未格式化价格)的自定义属性,方便JS读取计算,以产品卡片价格为例:
<span class="dynamic-price" data-origin-price="{{ product.price | times: 0.01 }}">
  {{ product.price | money }}
</span>

购物车、结算页的价格元素也按照相同规则添加data-origin-price属性即可。

2. 前端货币切换逻辑实现(JS实现)

  • 首先添加货币切换选择器,可放置在页头等公共位置:
<select id="currency-switcher">
  <option value="USD" {% if shop.currency == 'USD' %}selected{% endif %}>USD ($)</option>
  <option value="EUR" {% if shop.currency == 'EUR' %}selected{% endif %}>EUR (€)</option>
  <option value="CNY" {% if shop.currency == 'CNY' %}selected{% endif %}>CNY (¥)</option>
  <!-- 按需添加其他货币选项 -->
</select>
  • 编写JS逻辑实现价格换算、页面更新、用户选择留存:
// 货币符号映射表,按需补充
const currencySymbolMap = {
  'USD': '$',
  'EUR': '€',
  'CNY': '¥',
  'GBP': '£'
}

// 价格格式化函数,可根据需求调整小数位、千分位规则
function formatConvertedPrice(price, currency) {
  return `${currencySymbolMap[currency]}${price.toFixed(2)}`
}

// 批量更新页面所有价格
function refreshAllPrices(targetCurrency) {
  const exchangeRate = window.customExchangeRates[targetCurrency]
  document.querySelectorAll('.dynamic-price').forEach(priceEl => {
    const originPrice = parseFloat(priceEl.dataset.originPrice)
    const convertedPrice = originPrice * exchangeRate
    priceEl.innerText = formatConvertedPrice(convertedPrice, targetCurrency)
  })
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
  // 初始化切换器选中状态
  document.querySelector(`#currency-switcher option[value="${window.selectedCurrency}"]`).selected = true
  // 初始化价格展示
  refreshAllPrices(window.selectedCurrency)

  // 监听货币切换事件
  document.getElementById('currency-switcher').addEventListener('change', (e) => {
    const newCurrency = e.target.value
    window.selectedCurrency = newCurrency
    // 存储用户选择,下次访问直接生效
    localStorage.setItem('user_selected_currency', newCurrency)
    refreshAllPrices(newCurrency)
  })
})

3. 结算页汇率同步补充

以上逻辑仅实现前端展示价格的切换,如果你需要结算时也按照自定义汇率计算价格,普通店铺可以通过Shopify Cart API给商品添加自定义行属性传递换算后价格,Shopify Plus店铺可以直接使用脚本编辑器在结账阶段应用自定义汇率计算即可。


内容的提问来源于stack exchange,提问作者W O L E I __

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 21:48:00