如何给WordPress 单页面链接添加 .html 后缀
使用过 wordpress 的朋友都知道,wordpress 可以选择好几种固定连接,一般来说,我们为了对搜索引擎友好,都会选择伪静态的固定连接。
伪静态连接其一是对搜索引擎友好,其二是如果我们想要对 wordpress 进行加速,伪静态链接也是必不可少的。
我们一般设置 wordpress 的固定连接,会使用 2 种形式的,一种是文章名形式的,一种是 id 形式的,而我们在设置的时候一般会加上 html 后缀,这样伪静态的 url 更加规范了,比如文本的链接:
https://mybj123.com/aboutus.html
就是以 html 后缀形式结束的。
而如果在 wordpress 设置–固定连接加上 html 后缀之后,这个设置只能对 wordpress 的文章起作用,而对于 wordpress 的页面来说是不起作用的。
因此如果我们想要规范整站的 url,那么也可以通过代码或者插件将我们的页面也加上 html 后缀
两种方式实现
方法一:使用插件.html on PAGES
在你的 wordpress 后台–插件–安装插件搜索.html on PAGES 安装即可。
文章名: /%postname%.html
或者
数字连接(id): /%post_id%.html
两者皆可,如果是中文网站我们建议使用数字连接,因为如果中文网站的话,使用用文章名,还需要通过插件或者手工更改别名 ,比较麻烦。
需要注意的是,启用插件后还需要到后台固定链接设置中,重新保存一下设置,否则会跳到 404 页面,如果不成功可以先删除空间根目录的.htaccess 文件,之后保存会自动生成新的。
方法二:使用代码(代码提取于.html on PAGES 插件)
既然用插件可以实现,直接将插件中的代码集成到主题中同样也可以,代码提取自.html on PAGES 插件,将下面代码添加主题 functions.php 中即可。
// 页面链接添加 html 后缀 add_action('init', 'html_page_permalink', -1); function html_page_permalink() { global $wp_rewrite; if ( !strpos($wp_rewrite->get_page_permastruct(), '.html')){ $wp_rewrite->page_structure = $wp_rewrite->page_structure . '.html'; } }
添加后,就生效了吗?当然没有,我们还需要到固定链接设置页面,重新保存一下固定链接设置,否则不会生效。
上述代码适合伪静态的固定链接形式使用,比如:
/%postname%.html /%post_id%.html
效果如下:
另外,如果同时给 WordPress 分类目录和页面添加斜杠如下代码:
function nice_trailingslashit($string, $type_of_url) { if ( $type_of_url != 'single' && $type_of_url != 'page' && $type_of_url != 'single_paged' ) $string = trailingslashit($string); return $string; } add_filter('user_trailingslashit', 'nice_trailingslashit', 10, 2);
则还需要将该代码修改为:
// 添加斜杠 function nice_trailingslashit($string, $type_of_url) { if ( $type_of_url != 'single' && $type_of_url != 'page' ) $string = trailingslashit($string); return $string; } add_filter('user_trailingslashit', 'nice_trailingslashit', 10, 2);
排除页面文件,否则页面链接.html 后面也会自动加上斜杠。
想看具体实现效果在码云笔记网站底部有单页面,大家可以点进去试试
码云笔记 » 如何给WordPress 单页面链接添加 .html 后缀