首页 » WordPress » 怎样缓存 Sidebar

怎样缓存 Sidebar

今天尝试使用 PHP 的 Output Control Functions 进行缓存,发现代码还是蛮简单的,于是把其中对 Sidebar 缓存的代码分享下,几点说明:

1. 可以自己修改缓存时间,怎么修改,看下面代码的唯一的注释。
2. 一旦采用这样的缓存,在缓存时间内对 sidebar 做任何修改都不会生效。
3. 如果你又想缓存又想修改东西,你可以把缓存时间修改为1秒,作了修改之后,让 sidebar 缓存生成之后,再把缓存时间修改为原来的。
4. 如果你的 sidebar 为不同页面不同 sidebar,那么你要根据自己的 sidebar 生成不同 sidebar 缓存,如:sidebar_home, sidebar_single,基本代码类似。
5. 会对 Recent Post, Recent Comment 这些插件产生延迟,在缓存的时间内,如果这些列表更新了回不能及时体现。

下面是具体的步骤和代码:

1. 进入 WordPress 后台,点击 Design => Theme Editor => Sidebar (sidebar.php)。

2. 在 sidebar.php 开头加入以下代码:

<?php
$sidebar_html = ABSPATH . "wp-content/cache/sidebar.txt";
$have_cached = false;
if (file_exists($sidebar_html)){
    $file_time = filemtime($sidebar_html);
    if (($file_time + 3600) > time()){ //缓存1小时
        echo "<!-- cached sidebar -->";
        echo(file_get_contents($sidebar_html));
        echo "<!-- end of cached sidebar -->";
        $have_cached = true;
    }
}
if(!$have_cached){
    ob_start();
?>

3. 在 sidebar.php 结尾加入以下代码:

<?php
    $sidebar_content = ob_get_contents();
    ob_end_clean();
    $sidebar_fp = fopen($sidebar_html, "w");
 
    if ($sidebar_fp){
         fwrite($sidebar_fp, $sidebar_content);
         fclose($sidebar_fp);
    }
 
    echo $sidebar_content;
}
?>
标签:

分享到:

7 条评论 添加你的评论 →

  • 小七 2008-06-23 11:27:30 #

    Warning: fopen(e:\www\****/wp-content/cache/sidebar.txt) [function.fopen]: failed to open stream: No such file or directory in e:\www\****/wp-content\themes\Aspire\sidebar.php on line 138

    需要手动在wp-content下建cache文件夹

    支持 反对

  • 小七 2008-06-23 11:28:19 #

    速度的确快了很多啊~ 呵呵

    支持 反对

  • 菠菜 2008-06-23 12:44:51 #

    嗯,受教了。既然是好东西,咱也要用用。

    支持 反对

  • Charles 2008-06-23 16:57:58 #

    很强~

    支持 反对

  • 一亿度 2008-06-27 13:08:51 #

    我上次也缓存了sidebar,很多代码和楼主的很类似~

    我缓存的时间是10分钟,因为缓存太久的话,最近评论就看不到了:(

    支持 反对

  • neekey 2008-08-19 10:59:37 #

    不错的方法。不过随机文章之类的就没办法弄了

    支持 反对

发表评论

你必须 登陆 之后才能留言。你可以使用以下方式快速登陆我爱水煮鱼:

使用新浪微博登陆 使用腾讯微博登陆 使用豆瓣登陆

你也可选择直接在本站 注册