让分页文章也可以静态化

Posted by David on 2008-03-07 in Blog Related

WordPress 提供了多种结构标签,以便我们可以设置各种格式的永久链接结构,再配合一些静态化插件(例如 cos-html-cache),就可以使页面真正静态化。

不过 WordPress 对已分页文章的永久链接的处理方式则会给页面静态化后的访问带来问题。 例如,永久链接结构为 /%year%/%monthnum%/%postname%.html,WordPress 生成的文章相关分页链接如下所示:

yourdomain.com/2008/03/postname.html 
yourdomain.com/2008/03/postname.html/2 
yourdomain.com/2008/03/postname.html/3

可以看到 WordPress 只是简单地将页码加在了链接尾部,所以当我们静态化其中一页的内容后,我们将只能访问被静态化的那一页内容而无法访问其它分页的内容。为了可以静态化所有分页内容,需要对 WordPress 处理永久链接的方式做些小小的改动,并改变分页链接的形式:

yourdomain.com/2008/03/postname.html 
yourdomain.com/2008/03/postname-2.html
yourdomain.com/2008/03/postname-3.html


以前面提到的永久链接结构为例,作如下修改:

/*
  打开 wp-includes/rewrite.php 文件
  找到 $rewrite = array_merge($rewrite, array($match => $query))
  在这行代码之前添加以下代码:
*/
if (strpos($match, '.html') !== false && strpos($query, '&page=') !== false) {
  $match = str_replace('(/[0-9]+)?/?$', '$', $match);
  $rewrite = array_merge($rewrite, array(str_replace('([^/]+).html', '([^/]+)-([0-9]+).html', $match) => $query));
}

以上代码使 WordPress 可以处理第一页后面的分页链接。其实通过修改 .htaccess 也可以达到同样的效果。

除此之外还需要修改文章分页链接生成模板。打开 wp-includes/post-template.php 文件,修改 wp_link_pages 函数(这段代码不太好贴,点此查看)。

具体效果,可以点击这里还有这里查看。

Tags: , , .

Comments

  1. 1 ddkk3000

    :oops: 小白的问一下,如何修改“post-template.php”这个没有看懂,能不能贴一个完整的该文件出来?谢谢。

  2. 2 David

    @ddkk3000:
    将http://www.voidman.com/wp-content/uploads/2008/03/wp_link_pages.phps里的代码覆盖wp-includes/post-template.php 里的 wp_link_pages 函数就可以了

  3. 3 ddkk3000

    博主,我覆盖了以后,访问分页显示404未找到。

  4. 4 David

    @ddkk3000:
    wp-includes/rewrite.php 文件修改过后,要到后台设置里重新生成一下永久链接规则

  5. 5 rekey

    为何我修改了永久链接后(/html/%year%/%monthnum%/%day%/%postname%.html),分页面就出现问题,还原到默认永久链接,分页就能浏览,请教解决办法。

  6. 6 David

    @rekey:
    文中举例只适用于 /%year%/%monthnum%/%postname%.html 这样的永久链接结构

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>