jQuery提取URL路径追加到现有链接 解决WordPress多站点子页切换问题
问题排查
- 路径提取逻辑错误:
document.URL.split("/")[1]提取到的是https:后的空字符串,并非域名后的路径内容,且该写法只能拿到单个路径段,无法获取完整子路径。 - 缺少斜杠兼容处理:直接拼接站点根URL和路径时,若根URL末尾没有斜杠,会出现
https://example.commy-page这类无效链接。 - 没有过滤当前站点的语言前缀:比如你在法语站
/fr/my-page,切换到英文站时需要先去掉路径里的/fr前缀,否则会拼接出错误的重复前缀路径。
修正后的实现代码
jQuery(function ($) { // 获取当前页面完整路径(域名后的所有内容) const fullPath = window.location.pathname; // 定义已配置的语言前缀列表,后续新增语言直接扩展即可 const langPrefixes = ['en', 'fr', 'de']; // 去除路径中的语言前缀,拿到纯页面路径 let purePath = fullPath; for (const prefix of langPrefixes) { if (fullPath.startsWith(`/${prefix}/`) || fullPath === `/${prefix}`) { purePath = fullPath.replace(`/${prefix}`, ''); break; } } // 保留当前页面的查询参数和锚点(不需要可删除以下两行) const queryAndHash = window.location.search + window.location.hash; purePath = purePath + queryAndHash; // 批量更新所有语言切换链接 $('.en-link, .fr-link, .de-link').each(function () { const $link = $(this).find('a'); let baseUrl = $link.attr('href'); // 统一处理根URL末尾的斜杠 if (baseUrl.endsWith('/')) { baseUrl = baseUrl.slice(0, -1); } // 拼接完整跳转链接 $link.attr('href', `${baseUrl}${purePath}`); }); });
补充说明
如果后续需要新增语言,只需要在langPrefixes数组里新增对应语言标识,同时给菜单li加上对应[lang]-link的类名即可,不需要修改其他逻辑。
内容的提问来源于stack exchange,提问作者user16048796
相关产品推荐
相关产品推荐

