WordPress站点移除链接.html后缀的实现需求及问题
解决WordPress站点移除链接
.html后缀的问题 嘿,我明白你想把全站所有带.html后缀的链接改成干净的无后缀形式,之前用str_ireplace和gettext的思路方向对,但gettext过滤器其实更适合处理翻译文本,没法覆盖所有链接场景(比如动态生成的永久链接、菜单链接等)。下面给你一套完整的解决方案,覆盖不同场景的链接替换:
1. 替换文章/页面内容里的链接
针对文章、页面编辑器里的<a>标签链接,我们用the_content过滤器结合正则精准匹配href属性里的.html后缀,避免误替换文本中出现的.html:
function kb_remove_html_from_content_links($content) { // 正则匹配href中的.html后缀,仅替换链接末尾的.html $content = preg_replace('/(<a[^>]+href="[^"]+)\.html(")/i', '$1$2', $content); return $content; } add_filter('the_content', 'kb_remove_html_from_content_links');
2. 替换文章/页面的永久链接
如果站点永久链接结构原本带.html,或者主题/插件动态生成的文章/页面链接带后缀,用post_link和page_link过滤器处理:
function kb_remove_html_from_permalinks($permalink, $post) { if (strpos($permalink, '.html') !== false) { $permalink = str_replace('.html', '', $permalink); } return $permalink; } add_filter('post_link', 'kb_remove_html_from_permalinks', 10, 2); add_filter('page_link', 'kb_remove_html_from_permalinks', 10, 2);
3. 替换导航菜单里的链接
导航菜单的链接需要单独处理,用nav_menu_link_attributes过滤器修改菜单链接的href属性:
function kb_remove_html_from_menu_links($atts) { if (isset($atts['href']) && strpos($atts['href'], '.html') !== false) { $atts['href'] = str_replace('.html', '', $atts['href']); } return $atts; } add_filter('nav_menu_link_attributes', 'kb_remove_html_from_menu_links');
4. 替换文本小工具里的链接
如果站点用了文本小工具添加链接,加上这个过滤器覆盖:
function kb_remove_html_from_widget_links($content) { $content = preg_replace('/(<a[^>]+href="[^"]+)\.html(")/i', '$1$2', $content); return $content; } add_filter('widget_text_content', 'kb_remove_html_from_widget_links');
完整代码整合
把以上所有代码放到你的主题functions.php文件里,或者自定义插件中:
// 移除文章内容中的链接.html后缀 function kb_remove_html_from_content_links($content) { $content = preg_replace('/(<a[^>]+href="[^"]+)\.html(")/i', '$1$2', $content); return $content; } add_filter('the_content', 'kb_remove_html_from_content_links'); // 移除文章/页面永久链接的.html后缀 function kb_remove_html_from_permalinks($permalink, $post) { if (strpos($permalink, '.html') !== false) { $permalink = str_replace('.html', '', $permalink); } return $permalink; } add_filter('post_link', 'kb_remove_html_from_permalinks', 10, 2); add_filter('page_link', 'kb_remove_html_from_permalinks', 10, 2); // 移除导航菜单链接的.html后缀 function kb_remove_html_from_menu_links($atts) { if (isset($atts['href']) && strpos($atts['href'], '.html') !== false) { $atts['href'] = str_replace('.html', '', $atts['href']); } return $atts; } add_filter('nav_menu_link_attributes', 'kb_remove_html_from_menu_links'); // 移除文本小工具链接的.html后缀 function kb_remove_html_from_widget_links($content) { $content = preg_replace('/(<a[^>]+href="[^"]+)\.html(")/i', '$1$2', $content); return $content; } add_filter('widget_text_content', 'kb_remove_html_from_widget_links');
注意事项
- 替换后记得清除WordPress缓存(包括插件缓存、服务器缓存),否则可能看不到效果。
- 如果站点有自定义类型的文章,还可以添加
post_type_link过滤器来覆盖自定义文章类型的链接。 - 正则匹配已经尽量精准,即使是带参数的链接(比如
example.com/page.html?param=1),也能正常替换成example.com/page?param=1。
内容的提问来源于stack exchange,提问作者Christoph Schober
相关产品推荐
相关产品推荐

