电脑技术学习

WordPress 分页文章静态化的更优解决方案

dn001

利用 WordPress 本身提供的接口实现了更好的解决方案。

以/%year%/%monthnum%/%postname%.html这样的永久链接结构为例:

1. 打开主题目录下的functions.php文件,添加以下代码:

// 添加分页处理规则
function;add_custom_post_rewrite_rules($rules);{
;;$custom_rules;=;array(
; ;;'([0-9]{4})/([0-9]{1,2})/([^/]+)-([0-9]+)\.html$';=>;'index.php?year=$matches[1]&monthnum=$matches[2]&name=$matches[3]&page=$matches[4]',
;;);
;;$rules;=;array_merge($custom_rules,;$rules);
;
;;return;$rules;
}
add_filter('post_rewrite_rules',;'add_custom_post_rewrite_rules');
;
// 修改分页链接
function;my_wp_link_pages($args;=;'');{
;;$args;.=;($args;?;'&';:;'');.;'echo=0';
;;$links;=;wp_link_pages($args);
;;$links;=;preg_replace_callback('|([0-9]{4}/[0-9]{1,2}/)([^/]+)(\.html)(/)([0-9]+)|',;'custom_page_link',;$links);
;
;;echo;$links;
}
;
function;custom_page_link($matches);{
;;return;$matches[1].$matches[2].'-'.$matches[5].$matches[3];
}

2. 打开主题目录下的single.php文件,查找wp_link_pages并替换为my_wp_link_pages。

3. 后台“设置-永久链接点击一下“保存修改按钮,大功告成。

至于 life97 同学说的 .html/xxx 形式的链接访问失效,这个可能和服务器设置有关,具体原因我也不是很清楚,不过可以通过在 .htaccess 文件中添加规则来解决此问题,如:

<ifmodule mod_rewrite.c>
RewriteEngine On
RewriteBase;/
RewriteRule ^([0-9]{4})/([0-9]{1,2})/([^/]+)\.html/trackback/?$ index.php?year=$1&monthnum=$2&name=$3&tb=1;[L]
RewriteRule ^([0-9]{4})/([0-9]{1,2})/([^/]+)\.html/feed/(feed|rdf|rss|rss2|atom)/?$ index.php?year=$1&monthnum=$2&name=$3&feed=$4;[L]
RewriteRule ^([0-9]{4})/([0-9]{1,2})/([^/]+)\.html/(feed|rdf|rss|rss2|atom)/?$ index.php?year=$1&monthnum=$2&name=$3&feed=$4;[L]
</ifmodule>

标签: