WordPress 嵌入天气网 iframe:固定城市参数失效 + JS 自动获取访客城市方案

12次阅读
没有评论

前言

很多人在 WordPress 侧边栏、页面中嵌入天气网(tianqi.com)的天气 iframe 组件,想实现「固定城市」或者「自动识别访客所在城市」展示天气。但直接拼接 city=xxx 会发现不生效,同时也有需求想用 JS 动态拿到城市,再加载对应天气。本文把踩坑点、可用方案、完整代码一次性整理好。

一、问题:city=beijing 为什么无效

天气网旧文档里流传的 city= 参数已经废弃,直接写在 iframe 地址上不会生效。

  • ❌ 无效写法
<iframe src="https://i.tianqi.com/index.php?c=code&id=1&city=beijing"></iframe>
  • ✅ 官方参数改为 py=,值为城市小写拼音 同时还有一个隐藏坑:部分样式 ID 强制走 IP 自动定位,会忽略 py 参数,遇到这种情况更换 id 值测试即可,例如 id=17、id=19。

固定城市可用 iframe 示例(直接放进 WP 自定义 HTML)

<iframe name="weather_inc"
src="https://i.tianqi.com/index.php?c=code&id=1&icon=1&wind=1&num=2&py=beijing"
width="320" height="72"
frameborder="0"
marginwidth="0"
marginheight="0"
scrolling="no"
allowtransparency="true">
</iframe>

使用提示:

  1. 优先去天气网官方插件生成页,可视化选择样式、城市,拿到最新代码;
  2. WordPress 中使用【自定义 HTML】区块 / 小工具,不要用旧版文本小部件,容易过滤 iframe;
  3. 地址必须是 https,防止混合内容被浏览器拦截空白。

二、需求升级:JS 自动获取访客城市

浏览器本身不能直接读取访客 IP 和城市,两条主流路线:

  1. IP 归属接口:无需用户授权,适合天气展示;免费接口存在配额、跨域风险;
  2. GPS 定位 navigator.geolocation:弹窗请求用户授权,精度更高,用户拒绝就失效,拿到经纬度后还需要逆地理编码转城市。

示例 1:ipinfo.io 获取城市(前端直接调用)

async function getCity() {
  try {
    const res = await fetch('https://ipinfo.io/json');
    const geo = await res.json();
    console.log('城市:', geo.city);
    return geo.city;
  } catch (e) {
    console.error('获取城市失败', e);
    return 'beijing'; // 默认兜底城市拼音
  }
}

注意:该接口返回的是英文城市名,不一定和天气网 py 参数完全匹配,量大建议自建映射表。

示例 2:高德地图 Web API 获取本地城市(国内更稳定)

需要提前申请高德 Web 端 Key:

<script type="text/javascript" src="https://webapi.amap.com/maps?v=2.0&key=你的key"></script>
<script>
function getLocalCity(){
  const citySearch = new AMap.CitySearch();
  citySearch.getLocalCity(function(status, result) {
    if (status === 'complete' && result.info === 'OK') {
      console.log(result.city);
    }
  })
}
</script>

示例 3:拿到城市后动态加载天气 iframe

配合上面获取城市的方法,动态拼接天气地址,自动加载:

<div id="weather-box"></div>
<script>
async function getCity() {
  try {
    const res = await fetch('https://ipinfo.io/json');
    const geo = await res.json();
    return geo.city.toLowerCase();
  } catch (e) {
    return 'beijing';
  }
}
async function loadWeatherIframe() {
  const cityPy = await getCity();
  const iframe = document.createElement('iframe');
  iframe.name = 'weather_inc';
  iframe.src = `https://i.tianqi.com/index.php?c=code&id=1&icon=1&wind=1&num=2&py=${cityPy}`;
  iframe.width = "320";
  iframe.height = "72";
  iframe.frameBorder = "0";
  iframe.scrolling = "no";
  document.getElementById('weather-box').appendChild(iframe);
}
loadWeatherIframe();
</script>

示例 4:GPS 定位(需要用户同意)

function getGPSCity() {
  if (!navigator.geolocation) return Promise.reject('浏览器不支持定位');
  return new Promise((resolve, reject) => {
    navigator.geolocation.getCurrentPosition(pos => {
      const lat = pos.coords.latitude;
      const lng = pos.coords.longitude;
      resolve({ lat, lng });
    }, err => reject(err));
  })
}

三、常见坑汇总

  1. 参数不生效:区分 city(废弃)和 py(拼音);部分模板 ID 强制 IP 定位,换 ID 测试;
  2. iframe 空白:检查 HTTPS、安全插件 / WAF 是否拦截第三方域名;
  3. 城市名不匹配:不同 IP 接口返回城市名称格式不一样,需要做拼音映射;
  4. 缓存问题:WP 缓存插件会缓存静态页面,JS 动态代码一定要放在前端执行的 HTML 块;
  5. 免费接口限制:前端直接调用 IP 定位接口有调用上限,访问量大容易被封。

四、更稳定的推荐方案

如果网站流量较高,不建议前端直接调用第三方 IP 接口。最优方案:

  1. 在 WordPress 后端写简易接口,服务器读取访客 IP,解析城市;
  2. 后端返回城市拼音给前端;
  3. 前端拿到拼音再渲染天气 iframe。

也可以直接使用独立天气插件,不走 iframe 嵌入,避免第三方接口变动带来的失效风险。

五、备选方案

  • 天气网官方在线生成工具:https://www.tianqi.com/plugin/styleset,可视化配置;
  • 其他天气 iframe 服务商,如 2345 天气插件;
  • WP 插件:Location Weather、Free Weather 等,独立渲染天气。
正文完
可以使用微信扫码关注公众号(ID:xzluomor)
post-qrcode
 0
评论(没有评论)
验证码