我爱水煮鱼 » 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;
}
?>

标签:

分享到:

请选择你看完该文章的感受:

不错 超赞 无聊 扯谈 不解 路过
  1. 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文件夹

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

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