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

Posted by David on 2008-11-12 in Blog Related

之前用比较暴力的方式实现了分页文章的静态化,不过这样一来升级 Wordpress 就不太方便了。厌烦了每次升级都要修改源文件,于是利用 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>

注意添加顺序,不要置于 Wordpress 生成的规则之后。

下面是几种其它永久链接结构的具体修改代码:

Tags: , , , , .

Comments

  1. 1 alfiereply to this comment

    hello,

    请教一下,你的archive是怎么做的?方便分享一下你的archive.php吗?我很喜欢这种风格。

  2. 2 Davidreply to this comment
  3. 3 life97reply to this comment

    :lol: 好人哪,解燃眉之急,雪中送炭。而且还特意为我的永久链接格式而准备好只需下载就行,真的激动得无言表达。只能还是用这么简单的一句:谢谢。

  4. 4 Davidreply to this comment

    @life97:
    举手之劳而已 :-)

  5. 5 life97reply to this comment

    这个my_wp_link_pages,有没有办法像原来的wp_link_pages那样,可以自行定义样式?比如:my_wp_link_pages('before=&after=&next_or_number=text&previouspagelink=上一頁&nextpagelink=下一頁')

  6. 6 Davidreply to this comment

    @life97: 可以的

Leave a Reply

:mrgreen: :neutral: :twisted: :arrow: :shock: :smile: :???: :cool: :evil: :grin: :idea: :oops: :razz: :roll: :wink: :cry: :eek: :lol: :mad: :sad: :!: :?:

You can use these XHTML tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="">