zl程序教程

您现在的位置是:首页 >  其他

当前栏目

WordPress 技巧:使用文件缓存侧边栏

文件缓存WordPress 使用 技巧 侧边
2023-06-13 09:18:33 时间

今天尝试使用 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 后台,点击外观 => 主题编辑 => 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;
}
?>