一直没有怎么使用nextpage这个分页标签,这两天查看自己以前写的一篇文章,发现无法打开分页,一打开就是404的错误。应该是使用了cos-html-cache缓存插件的缘故,所有页面都静态化了。所以造成了分页功能的无法使用。在网上找了很多办法,都没解决这个问题。终于在VoidMan的博客中找到了解决方法。

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/ 添加分页处理规则
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. 后台“设置-永久链接”点击一下“保存修改”按钮,大功告成。

一般到这里就可以了,如果有人还不能正常使用分页功能,那么可能还需要改一下.htaccess,具体修改方法如下:

1
2
3
4
5
6
7
<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>

注意添加顺序,不要置于 WordPress 生成的规则之后。其它永久链接结构的具体修改代码请参考VoidMan的博客